Advanced-Web-Programming-munotes

Page 1

1 1
INTRODUCING .NET
Unit Structure
1.0 Objectives
1.1 Introducing .NET
1.1.1 C#, VB, and the .NET Languages
1.1.2 Intermediate Language
1.1.3 Components of .Net Framework
1.1.4 Common Language Runtime (CLR)
1.1.5 The .NET Class Library
1.1.6 Common Type S ystem (CTS)
1.1.7 Meta Data in .NET
1.1.8 Common Language Specification (CLS)
1.5 Example Programs
1.6 Summary
1.7 Exercise
1.8 Reference
1.0 OBJECTIVE
After going through this unit you will be able to,
1. Create and Console Application with basics code.
2. Crea te the Application using different types of statements and loops.
3. Know about namespaces and assemblies and how to create the same.
4. Create console application using delegates and methods.
1.1 THE .NET FRAMEWORK
• Microsoft .NET is much more than XML Web services.
• At the heart of Microsoft .NET is the .NET Framework, consisting
of the common la nguage runtime and the class libraries.
• These two components provide the execution engine and
programming APIs for building .NET applications.
• Applications compiled for the .NET Framework are not compiled
directly to native code. Instead, they are compile d into an munotes.in

Page 2


2 Advanced Web
Programming
2 intermediate language called Microsoft Intermediate Language
(MSIL).
• When an application is run for the first time, the common language
runtime just -in-time compiler compiles the MSIL code into native
code before it is executed.
• The common lang uage runtime is more than a simple JIT compiler;
it is also responsible for providing low -level execution services,
such as
• garbage collection,
• exception handling,
• security services, and
• Run time type -safety checking.
• Because of the common language run time's role in managing
execution, programs that target the .NET Framework are sometimes
called " managed" applications.
• The .NET Framework also includes a set of classes for building
applications that run on the common language runtime.
• These class librar ies provide rich support for a wide range of tasks,
including data access, security, file IO, XML manipulation,
messaging, class reflection, XML Web services, user -interface
construction, text processing, ASP.NET, and Microsoft Windows
services.
• The most u nique attribute of the .NET Framework is its support for
multiple languages.
• It provides support for over 20 programming languages including
Perl, Python, and COBOL.
• Relying on the common language runtime, code compiled with these
compilers can interoper ate.
• The .NET Framework is composed of the four extended applications
named as four blue boxes —representing
1. ASP.NET,
2. Windows Forms,
3. ADO.NET and
4. XML, and subcomponents. munotes.in

Page 3


3
Introducing .NET

This book uses the Visual Basic language, which enables you to create
readable, mod ern code. The .NET version of VB is similar in syntax to
older flavors of VB that you may have encountered, including “classic”
VB 6 and the Visual Basic for Applications (VBA) language often used to
write macros in M icrosoft Office programs.
1.1.1 C#, VB, and the .NET Languages
• This book uses the Visual Basic language, which enables you to
create readable, modern code. The .NET version of VB is similar in
syntax to older flavors of VB that you may have encountered,
including “classic” VB 6 and the Visual B asic for Applications
(VBA) language often used to write macros in Microsoft Office
programs such as Word and Excel. However, you cannot convert
classic VB into the .NET flavor of Visual Basic, just as you cannot
convert C++ into C#.
• This book uses C#, Mic rosoft’s .NET language of preference. C#
resembles Java, JavaScript, and C++ in syntax, so programmers who
have coded in one of these languages will quickly feel at home.
Interestingly, VB and C# are quite similar. Though the syntax is
different, both VB a nd C# use the .NET class library and are
supported by the CLR. In fact, almost any block of C# code can be
translated, line by line, into an equivalent block of VB code (and
vice versa). An occasional language difference pops up, but for the
most part, a d eveloper who has learned one .NET language can
move quickly and efficiently to another. munotes.in

Page 4


4 Advanced Web
Programming
4 • There are even software tools that translate C# and VB code
automatically (see http://converter.telerik.com or
http://tangiblesoftwaresolutions.com for examples).
• In short, both VB and C# are elegant, modern languages that are
ideal for creating the next generation of web applications.
1.1.2 Intermediate Language
• All the .NET languages are compiled into another lower -level
language before the code is executed. This lowe r level language is
the Common Intermediate Language (CIL, or just IL).
• The CLR, the engine of .NET, uses only IL code. Because all .NET
languages are based on IL, they all have profound similarities. This
is the reason that the VB and C# languages provid e essentially the
same features and performance.
• In fact, the languages are so compatible that a web page written with
C# can use a VB component in the same way it uses a C#
component, and vice versa.
• The .NET Framework formalizes this compatibility with something
called the Common Language Specification (CLS).
• Essentially, the CLS is a contract that, if respected, guarantees that a
component written in one .NET language can be used in all the
others.
• One part of the CLS is the common type system (CTS), which
defines the rules for data types such as strings, numbers, and arrays
that are shared in all NET languages.
• The CLS also defines object -oriented ingredients such as classes,
methods, events, and quite a bit more.
• For the most part, .NET developers don’t need to think about how
the CLS works, even though they rely on it every day.
• Following Figure shows how the .NET languages are compiled to
IL.
• Every EXE or DLL file that you build with a .NET language
contains IL code.
• This is the file you deploy to other computers. In the case of a web
application, you deploy your compiled code to a live web server. munotes.in

Page 5


5
Introducing .NET

Language compilation in .NET
1.1.3 Components of .NET Framework
• The following pointers descri be the components of the .Net
framework 3.5 and the j ob they perform:
Common Language Runtime:
• It is built around CTS. It performs runtime tasks like memory
management and garbage collection.

Base Class Libraries:
• It is a rich set of functional base classes. munotes.in

Page 6


6 Advanced Web
Programming
6 Extended Class Libraries:
• Extended from base cla ss libraries and designed to make it easier
and faster to develop a specific application.
CLS: (Common Language Specification)
• It defines requirements for .net languages. It contains the
specifications for the .Net supported languages and implementation
of language integration.
CTS: (Common Type System)
• It provides guidelines for declaring, using and managing types at
runtime and cross -language communication.
Metadata and Assemblies:
• Metadata is the binary information describing the program, which is
either stored in a portable executable file(PE) or in the memory.
• Assembly is a logical unit consisting of the assembly manifest, type
metadata, IL code and a set of resources like image files.
Multiple programming languages:
• It provides unified programming mod el for several languages.
Visual Studio .net:
• It is the IDE for coding with .net framework that spans the entire .net
framework.
Windows & COM+ services:
• Today’s requirements for today’s .net framework SDK is Windows
and COM+ services which provides faci lity to access the lower level
system functionality.
• The class framework encapsulates the following functionality:
• Data Access
• Thread management
• Interoperability with unmanaged code
• Network protocol support
• XML support
• Web services support and Windows For ms support Access
to assembly meta data
munotes.in

Page 7


7
Introducing .NET 1.1.4 Common Language Runtime
• The CLR provides a rich level of support that simplifies application
development and provides for better code reuse.
• The CLR provides a broad set of runtime services, including
compilat ion, garbage collection and memory management.
• The CLR is built around the CTS, which defines standard, object -
oriented data types that are used across all .NET programming
languages.
• Code that runs under the control of the CLR is called managed code.
Managed code allows the CLR to do the following.
• Read meta data that describes the component interfaces and
types
• walk the code stack
• handle exceptions
• retrieve security information
Design Goals of the CLR:
1. Simplify Development
• Define standards that promote code reuse
• provide a broad range of services, including memory
management and garbage collection
2. Simplify application deployment
• Components use meta data instead of registration
• support side -by-side, multiple component versions
• command -line deployment (Xc opy) and uninstall(DEL)
3. support development languages
• provide rich base classes for developer tools and languages
4. support multiple languages
• define CTS that are used by all .NET languages
5. enable convergence of programming models
• Build languages and tools o n a common framework. For
example, ASP .NET, VB .NET, and C# have access to the
same base classes. munotes.in

Page 8


8 Advanced Web
Programming
8 Structure of the CLR:

1.1.5 The .NET Class Library
• The .NET class library is a giant repository of classes that provide
prefabricated functionality for e verything from reading an XML file
to sending an e -mail message.
• If you’ve had any exposure to Java, you may already be familiar
with the idea of a class library. However, the .NET class library is
more ambitious and comprehensive than just about any othe r
programming framework.
• Any .NET language can use the .NET class library’s features by
interacting with the right objects.
• This helps encourage consistency among different .NET languages
and removes the need to install numerous components on your
comput er or web server.
• Some parts of the class library include features you’ll never need to
use in web applications (such as the classes used to create desktop
applications with Windows interfaces). Other parts of the class
library are targeted directly at we b development.
• Still more classes can be used in various programming scenarios and
aren’t specific to web or Windows development.
• These include the base set of classes that define common variable
types and the classes for data access, to name just a few.
1.1.6 Common Type System
• CTS defines standard, object oriented types and value types that are
supported by all .NET programming languages.
• The CTS standards are what allow .NET to provide a unified
programming model, and to support multiple languages. munotes.in

Page 9


9
Introducing .NET • CTS is the first prerequisite for allowing languages to interoperate.
• This is easy to understand, if you consider that languages can only
interoperate if they are based on the same system of types.
• In the past, type discrepancies have caused many inter operability
problems, particularly for VB developers.
• So, CTS is an important new feature in the .NET framework. The
CTS must support a range of languages, some of which are object -
oriented, and some of which are not. Much has been made of the
fact tha t COBOL is now a first class .NET language. COBOL is a
procedural language, not an object -oriented one.
• The CTS provides two main types:
• Value Types
• Reference Types
Value types are further classified into
• Built -in types
• User defined types
Reference types are further classified into
• Pointers
• Objects
• Interfaces
• Value types are simple data types that roughly correspond to simple
bit patterns like integers and floats.
• In .NET, a value type derives from th e System. Object namespace,
and supports an inter face that provides information about the kind of
data that is stored, as well as the data value.
• They are useful for representing simple data types, and nay not -
object user defined type, including enumerations.
• They are known as exact types which mean t hat they fully describe
the value they hold.
• Reference types are also derived from the system.
• Object namespace, and may hold object references.
• They are self typing, which means that they describe their own
interface.
• They are very specific to the t ype of object you are assigning.
• Once the reference is assigned, you expect to query the object
reference according to what its interface provides. munotes.in

Page 10


10 Advanced Web
Programming
10 Some of the primitive data types are:
• Bool
• Char
• int 8
• int 16
• float 32
• float 64
• unsigned int8
• unsigned int1 6
Type Safety:
• The CTS promotes type safety, which in turn improves code
stability.
• In .NET, type safety means that type definitions are completely
known, and cannot be compromised.
• The CTS ensures that object references are strongly typed.
• It chec ks whether the array index out of range or not, whether the
arithmetic exceptions are handled properly or not etc.
1.1.7 Metadata in .NET
Meta Data is organized information that the CLR uses to provide compile
time and runtime services, including:
• Loading of class files
• Memory Management
• Debugging
• Object Browsing
• MSIL translation no Native Code
• NET components are self describing, because the Meta Data is
stored as part of the compiled component known in .NET as an
assembly.
• Combine this with the fact tha t .NET components do not require
windows registry entries, and you can immediately appreciate why
deployments are so much easier in .NET.
munotes.in

Page 11


11
Introducing .NET The figure below illustrates different Meta Data Consumers : profilerdesignersdebuggerProxy generatorreflection
Meta DataCode
Type BrowserOther IL CompilersSchemaGeneratorser ializ ation
CONTENTS OF META DATA
• Description of the assembly (the d eployment unit)
• identity: name, version and culture
• dependencies (other assemblies)
• security permission that the assembly requires to run
• Description of the Types
• Base classes and interfaces
• Custom attributes
• defined by the User
• defined by the Comp iler
• defined by the Framework
1.1.8 Common Language Specification(CLS)
• The purpose of the NET framework is to define standards that makes
it easier to write robust, secure and reusable code.
• The NET framework extends this concept by allowing any language
to part icipate in the framework; so long as it conforms to the
specifications embodied by the common Type System and the
Common Language Specification. munotes.in

Page 12


12 Advanced Web
Programming
12 • The common language Specification (CLS) defines conventions that
languages must support in order to be interope rable within .NET.
• The CLS defines rules that range from naming conventions for
interface members, to rules governing method overloading.
• In order to provide interoperation, a CLS -compliant language must
obey the following conventions:
• Public identifiers are case - sensitive.
• Language must be able to resolve identifiers that are equivalent to
their keywords.
• Stricter overloading rules; a given method name may refer to any
number of methods, as long as each one differs in the number of
parameters, or argume nt types.
• Properties and events must follow strict naming rules.
• All pointers must be managed, and reference must be typed;
otherwise, they cannot be verified.
1.5 EXAMPLE PROGRAMS Command Line Arguments using System;
class Program
{
public static v oid Main(string[] args)
{
Console.WriteLine("Enter The Name =");
string name = Console.ReadLine();
Console.WriteLine("Enter The Roll No.=");
int rollno = Int32.Parse (Console.ReadLine()); // Convert.ToInt32()
Console.WriteLine("Enter The Percentage :");
double per = Double.Parse(Console.ReadLine());
// Convert.ToDouble()
// Console.WriteLine("Name=" + name);
// Console.WriteLine("Roll No.=" + rollno);
// Console.WriteLine( "Percentage =" + per);
Console.WriteLine("name={0} \t rollno={1} \t Percentage={2}",
name, rollno, per);
Console.ReadKey(); // To hold the output
}
} munotes.in

Page 13


13
Introducing .NET Boxing and Unboxing using System;
class Program
{
public static void Main(strin g[] args)
{
int a = 10; // Value Type
object obj = a; // Refence Type
Console.WriteLine("a={0} ", a);
Console.WriteLine("obj={0}", obj);
int b = (int) obj ;
Console.WriteLine("b={0}", b);
Conso le.ReadKey(); // To hold the output
}
} Conditional Operator ?: using System;
class Program
{
public static void Main(string[] args)
{

Console.WriteLine("Enter The FOUR Numbers=");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = Convert.ToInt32(Console.ReadLine());
int d = Convert.ToInt32(Console.ReadLine());

int large = a > b ? a : b;
int larger = large > c ? large : c;
int larg est = larger > d ? larger : d;
Console.WriteLine("Large={0}", largest);
Console.ReadKey(); // To hold the output
}
} munotes.in

Page 14


14 Advanced Web
Programming
14 WAP to accept a number from the user and check whether it is positive ,
negative or zero. using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter The Number");
int num = Convert.ToInt32(Console.ReadLine());

if (num > 0)
{
Console.WriteLine("Positive Number");
}
if (num < 0)
{
Console.WriteLine("Negative Number");
}
if (num == 0)
{
Console.WriteLine("Number is ZERO");
}
Console.ReadKey(); // To hold the output
}
} WAP to accept a number fr om the user and check whether it is even or
odd. using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter The Number");
int num = Convert.ToInt32(Console.ReadLine());

if (num % 2 == 0 ) munotes.in

Page 15


15
Introducing .NET {
Console.WriteLine("Even Number");
}
else
{
Console.WriteLine("Odd Number");
}
Console.ReadKey(); // To hold the output
}
} Fall-through in Switch using System;
class Progr am
{
public static void Main(string[] args)
{
Console.WriteLine("Enter The Option");
int opt = Convert.ToInt32(Console.ReadLine());

switch (opt)
{
case 1:
Console.WriteLine("ONE");
goto case 3;
case 2:
Console.WriteLine("TWO");
break;
case 3:
Console.WriteLine("THREE");
break;
case 4:
Console.WriteLine("FOUR") ;
break;
default :
Console.WriteLine("Invalid Option"); munotes.in

Page 16


16 Advanced Web
Programming
16 break;
}
Console.ReadKey(); // To hold the output
}
} While Loop using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Incremented Loop");
int i = 1;
while (i <= 10)
{
Console.Write(i + " \t");
i++;
}
Console.WriteLine(" \nDecremented Loop");
int j = 10;
while (j >= 1)
{
Console.Write(j + " \t");
j--;
}
Console.ReadKey();
}
} do while Loop int i = 1;
do
{
Console.Write(i + " \t");
i++;
} while ( i <= 10);

int j = 10; munotes.in

Page 17


17
Introducing .NET do
{
Console.Write(j + " \t");
j--;
} while (j > 0); For Loop Console.WriteLine("Incremented Loop");
for (int i = 1; i <= 10; i++)
{
Console.Writ e(i + "\t");
}
Console.WriteLine ("Decremented Loop")
for(int j=10;j>=1;j --)
{
Console.Write (j+" \t");
}
Foreach Loop int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

for (int i = 0; i < 10; i++ )
{
Console.Write(num[i] + " \t");
}
foreach(int s in num)
{
Console.Write(s + " \t");
} 1.6 SUMMARY
This chapter 1 gives the basic syntax of C#. It discusses about variables,
keywords, data ty pes, creation of arrays, operators, control structures,
methods debugging and few example programs. After learning the above
topics, you can write many useful programs and built a strong foundation
for larger programming projects.
munotes.in

Page 18


18 Advanced Web
Programming
18 1.7 EXERCISE: REVIEW QU ESTIO NS
Chapter 1
1) Write a note on .NET Framework.
2) Explain the data types in C#.
3) Explain the various operators in C#.
4) Discuss the various looping structures in C#.
5) Explain how arrays are created in C#.
6) What is a method? Explain its compon ents.
7) How is debugging done in C#?

Program
1) WAP to accept a character from the user and check whether it is
vowel or not.
2) WAP to accept two numbers from the user and display the greater
number using if...else.
3) WAP to accept three numbers from the user an d display the greater
number.
4) WAP to accept a year from the user and display whether it is leap
year or not.
5) WAP to accept a number from the user and display the factorial.
6) WAP to accept a number from the user and display sum of digits and
reverse of that numb er.
7) WAP to accept a number from the user and check whether it is
palindrom number or not.
8) WAP to accept a number from the user and check w hether it is
armstrong number or not.
9) WAP to accept a number from the user and check w hether it is
prime number or not.
10) WAP to accept two numbers from the user and display the GCD and
LCM of that numbers.
11) WAP to accept a number from the user and check whether it is
perfect number or not?
a. Example : 6 -> 1+2+3 = 6 28 = 1 + 2 + 4 + 7 + 14 = 28 munotes.in

Page 19


19
Introducing .NET 12) WAP to display all the prim e numbers between 1 to 1000?
13) WAP to display all the armstrong numbers between 1 to 1000?
14) WAP to display the following output :









1.8 REFERENCE
1) The Complete Reference: C#
2) Visu al C# 2012: How to program.
3) https://docs.microsoft.com/en -us/dotnet/csharp/
 Numbers Factorials 1 1 2 2 3 6 4 24 5 120 6 720 munotes.in

Page 20


20 Advanced Web Programming
20 2 THE C# LANGUAGE Unit Structure 2.0 The C# Language 2.1 Introduction 2.2 The .NET Languages 2.3 C# Language Basics 2.4 Variables and Data Types 2.5 Variables Operations 2.6 Keywords in C# 2.7 Object-Based Manipulation 2.7.1 The String Type 2.7.2 The Date Time and Time Span Types 2.7.3 The Array Type 2.8 Conditional Logic 2.8.1 Conditional Statements 2.9 Loops in C# 2.9.1 The for Loop 2.9.2 The foreach Loop 2.9.3 The While Loop 2.10 Methods in C# 2.10.1 Parameters 2.10.2 Method Overloading 2.11 Delegates 2.12 Summary 2.13 Questions 2.14 References 2.1 INTRODUCTION  Before you can create an ASP.NET application, you need to choose a .NET language in which to program it.  Both VB and C# are powerful, modern languages, and you won’t go wrong using either of them to code your web pages.  Often the choice is simply a matter of personal preference or your work environment. For example, if you’ve already programmed in a munotes.in

Page 21


21 The C# Language language that uses C-like syntax (for example, Java), you’ll probably be most comfortable with C#. Or if you’ve spent a few hours writing Microsoft Excel macros in VBA, you might prefer the natural style of Visual Basic. Many developers become fluent in both. This chapter presents an overview of the C# language.  You’ll learn about the data types you can use, the operations you can perform, and the code you’ll need to define functions, loops, and conditional logic.  This chapter assumes that you have programmed before and are already familiar with most of these concepts—you just need to see how they’re implemented in C#. If you’ve programmed with a similar language such as Java, you might find that the most beneficial way to use this chapter is to browse through it without reading every section.  This approach will give you a general overview of C#.  You can then return to this chapter later as a reference when needed. But remember, though you can program an ASP.NET application without mastering all the language details, this deep knowledge is often what separates the casual programmer from the true programming guru. 2.2 THE .NET LANGUAGES  The .NET Framework ships with two core languages that are commonly used for building ASP.NET applications: C# and VB.  These languages are, to a large degree, functionally equivalent. Microsoft has worked hard to eliminate language conflicts in the .NET Framework.  These battles slow down adoption, distract from the core framework features, and makes it difficult for the developer community to solve problems together and share solutions.  According to Microsoft, choosing to program in C# instead of VB is just a lifestyle choice and won’t affect the performance, interoperability, feature set, or development time of your applications.  Surprisingly, this ambitious claim is essentially true.  .NET also allows other third-party developers to release languages that are just as feature-rich as C# or VB.  These languages (which include Eiffel, Pascal, and even COBOL) “snap in” to the .NET Framework effortlessly.  In fact, if you want to install another .NET language, all you need to do is copy the compiler to your computer and add a line to register it in a configuration file. munotes.in

Page 22


22 Advanced Web Programming
22  Typically, a setup program would perform these steps for you automatically.  Once installed, the new compiler can transform your code creations into a sequence of Intermediate Language (IL) instructions, just as the VB and C# compilers do with VB and C# code.  IL is the only language that the Common Language Runtime (CLR) recognizes.  When you create the code for an ASP.NET web form, it’s changed into IL using the C# compiler (csc.exe) or the VB compiler (). Although you can perform the compilation manually, you’re more likely to let ASP.NET handle it automatically when a web page is requested. 2.3 THE C# LANGUAGE  New C# programmers are sometimes intimidated by the quirky syntax of the language, which includes special characters such as semicolons (;), curly braces ({}), and backward slashes (\).  Fortunately, once you get accustomed to C#, these details will quickly melt into the background.  In the following sections, you’ll learn about four general principles you need to know about C# before you learn any other concepts. Case Sensitivity  Some languages are case-sensitive, while others are not. Java, C, C++, and C# are all examples of case-sensitive languages.  VB is not. This difference can frustrate former VB programmers who don’t realize that keywords, variables, and functions must be entered with the proper case.  For example, if you try to create a conditional statement in C# by entering If instead of if, your code will not be recognized, and the compiler will flag it with an error when you try to build your application. Commenting  Comments are lines of descriptive text that are ignored by the compiler. C# provides two basic types of comments.  The first type is the single-line comment. In this case, the comment starts with two forward slashes and continues for the entire current line: // A single-line C# comment.  Optionally, C# programmers can use /* and */ comment brackets to indicate multiple-line comments: /* A multiple-line C# comment. */ munotes.in

Page 23


23 The C# Language  This way, the code won’t be executed, but it will still remain in your source code file if you need to refer to it or use it later. Statement Termination  C# uses a semicolon (;) as a statement-termination character.  Every statement in C# code must end with this semicolon, except when you’re defining a block structure. (Examples of such statements include methods, conditional statements, and loops, which are three types of code ingredients that you’ll learn about later in this chapter.) By omitting the semicolon, you can easily split a statement of code over multiple physical lines.  You just need to remember to put the semicolon at the end of the last line to end the statement.  The following code snippet demonstrates four equivalent ways to perform the same operation (adding three numbers together): // A code statement on a single line.
myValue = myValue1 + myValue2 + myValue3;
// A code statement split over two lines.
myValue = myValue1 + myValue2 +
myValue3;
// A code statement split over thr ee lines.
myValue = myValue1 +
myValue2 +
myValue3;
// Two code statements in a row.
myValue = myValue1 + myValue2;
myValue = myValue + myValue3; Blocks  The C#, Java, and C languages all rely heavily on curly braces—parentheses with a little more attitude: {}.  You can find the curly braces to the right of most keyboards (next to the P key); they share a key with the square brackets: [].  Curly braces group multiple code statements together. Typically, you’ll group code statements because you want them to be repeated in a loop, executed conditionally, or grouped into a function. These are all block structures, and you’ll see all these techniques in this chapter. munotes.in

Page 24


24 Advanced Web Programming
24  But in each case, the curly braces play the same role, which makes C# simpler and more concise than other languages that need a different syntax for each type of block structure. {
// Code statements go here.
} 2.4 VARIABLES AND DATA TYPES Variables  As with all programming languages, you keep track of data in C# by using variables.  Variables can store numbers, text, dates, and times, and they can even point to full-fledged objects.  When you declare a variable, you give it a name and specify the type of data it will store.  To declare a local variable, you start the line with the data type, followed by the name you want to use. A final semicolon ends the statement. // Declare an integer variable named errorCode.
int errorCode;
// Declare a string variable named myName.
string myName; The variables in C#, are categorized into the following types:  Value types  Reference types  Object types Value Type  Value type variables can be assigned a value directly. They are derived from the class System.ValueType.  The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value. For example if you type
Console.WriteLine(sizeof(int)),
you will get the output as 4, the bytes occupied by an integer. munotes.in

Page 25


25 The C# Language Reference Type  The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.  In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value.  Example of built-in reference types are:  object,  dynamic, and  string. Object Type  The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class.  The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types.  However, before assigning values, it needs type conversion. Data Types  The types of data that a variable contain is called Datatype. A Datatype is a classification of things that share similar type of qualities or characteristics or behaviour .  C# is strongly typed language so every variable and object must have a type.  These are two types of data type in C#. Primitive types or predefined  Eg:-byte, short, int, float, double, long, char, bool, DateTime, string object etc. Non-primitive types or user defined  Eg:- class , struct, enum, interface, delegate, array. Strings and Escaped Characters  C# treats text a little differently than other languages such as VB. It interprets any embedded backslash (\) as the start of a special character sequence.  For example, \n means add a new line (carriage return).  The most useful character literals are as follows:  \" (double quote) munotes.in

Page 26


26 Advanced Web Programming
26  \n (new line)  \t (horizontal tab)  \\ (backward slash) You can also insert a special character based on its hex code by using the syntax \x250. This inserts a single character with hex value 250 (which is a character that looks like an upside-down letter a).  Note that in order to specify the backslash character (for example, in a directory name), you require two slashes. Here’s an example: Alternatively, you can turn off C# escaping by preceding a string with an @ symbol, as shown here: string path = @"c:\MyApp\MyFiles"; 2.5 VARIABLES OPERATIONS
 You can use all the standard types of variable operations in C#.  When working with numbers, you can use various math symbols, as listed in Table below C# follows the conventional order of operations, performing exponentiation first, followed by multiplication and division and then addition and subtraction. You can also control order by grouping sub expressions with parentheses: Operator Description Example + Addition 1 + 1 = 2
- Subtraction 5 - 2 = 3
* Multiplication 2 * 5 = 10
/ Division 5.0 / 2 = 2.5
% Gets the remainder left after integer division 7 % 3 = 1  The operators above are designed for manipulating numbers. However, C# also allows you to use the addition operator ( + ) to join two strings: // A C# variable holding the path c:\MyApp \MyFiles
string path = "c: \\MyApp \\MyFiles";

int num ber;
number = 4 + 2 * 3;// number will be 10.
number = (4 + 2) * 3;
// number will be 18. munotes.in

Page 27


27 The C# Language // Join three strings together.
myName = firstName + " " + lastName;
In addition, C# provides special shorthand ass ignment operators.
Here are a few examples:
// Add 10 to myValue. This is the same as myValue = myValue + 10;
myValue += 10;
// Multiple myValue by 3. This is the same as myValue = myValue * 3;
myValue *= 3;
// Divide myValue by 12. This is the same as myV alue = myValue / 12;
myValue /= 1 2; 2.6 KEYWORDS IN C#  Keywords are predefined, reserved identifiers that have special meanings to the compiler.  They cannot be used as identifiers in your program unless they include @ as a prefix. There are 77 keywords.  Some of them are: is, base, checked, decimal, delegate, event, explicit, extern, fixed, for each, implicit, in, internal, is, lock ,object , override, params, read only, ref, sealed, stack, alloc, unchecked, unsafe, using. Type Conversions  Converting information from one data type to another is a fairly common programming task.  For example, you might retrieve a user’s text input that contains the number you want to use for a calculation.  Or, you might need to take a calculated value and transform it into text you can display in a web page. Conversions are of two types: widening and narrowing. Widening conversions always succeed.  For example, you can always convert a 32-bit integer into a 64-bit integer. You won’t need any special code: int mySmallValue;
long myLargeValue;
// Get the larg est possible value that can be stored as a 32 -bit integer.
// .NET provides a constant named Int32.MaxValue that provides this
number.
mySmallValue = Int32.MaxValue;
// This always succeeds. No matter how large mySmallValue is,
// it can be contained in my LargeValue.
myLargeValue = mySmallValue; munotes.in

Page 28


28 Advanced Web Programming
28  On the other hand, narrowing conversions may or may not succeed, depending on the data.  If you’re converting a 32-bit integer to a 16-bit integer, you could encounter an error if the 32-bit number is larger than the maximum value that can be stored in the 16-bit data type.  All narrowing conversions must be performed explicitly. C# uses an elegant method for explicit type conversion.  To convert a variable, you simply need to specify the type in parentheses before the expression you’re converting.  The following code shows how to change a 32-bit integer to a 16-bit integer: int count32 = 1000;
short count16;
// Convert the 32 -bit integer to a 16 -bit integer.
// If count32 is too larg e to fit, .NET will discard some of the
// information you need, and the resulting number will be
incorrect.
count16 = (short)count32; This process is called as Casting. 2.7 OBJECT-BASED MANIPULATION  .NET is object-oriented to the core. In fact, even ordinary variables are really full-fledged objects in disguise.  This means that common data types have the built-in smarts to handle basic operations (such as counting the number of characters in a string).  Even better, it means you can manipulate strings, dates, and numbers in the same way in C# and in VB.  You’ll learn far more about objects in Chapter 3. But even now it’s worth taking a peek at the object underpinnings in seemingly ordinary data types.  For example, every type in the .NET class library includes a ToString() method.  The default implementation of this method returns the class name. munotes.in

Page 29


29 The C# Language  In simple variables, a more useful result is returned: the string representation of the given variable.  The following code snippet demonstrates how to use the ToString() method with an integer: string myString;
int myInteger = 100;
// Convert a number to a string. myString will have the contents
"100".
myString = myInteger.ToString(); 2.7.1 The String Type  One of the best examples of how class members can replace built-in functions is found with strings.  In the past, every language has defined its own specialized functions for string manipulation.  In .NET, however, you use the methods of the String class, which ensures consistency between all .NET languages.  The following code snippet shows several ways to manipulate a string by using its object nature: string myString = "This is a test string ";
myString = myString.Trim(); // = "This is a test string"
myString = myString.Substring(0, 4); // = "This"
myString = myString.ToUpper(); // = "THIS"
myString = myString.Replace("IS", "AT"); // = "THAT"
int length = myString.Length; // = 4  The first few statements use built-in methods, such as Trim(), Substring(), ToUpper(), and Replace().  These methods generate new strings, and each of these statements replaces the current myString with the new string object.  The final statement uses a built-in Length property, which returns an integer that represents the number of characters in the string.  Note that the Substring() method requires a starting offset and a character length.  Strings use zero-based counting. This means that the first letter is in position 0, the second letter is in position 1, and so on. munotes.in

Page 30


30 Advanced Web Programming
30  You’ll find this standard of zero-based counting throughout .NET Framework for the sake of consistency. Methods in System.String Class Length() Returns the number of characters in the string (as an integer). ToUpper() and ToLower() Returns a copy of the string with all the characters changed to uppercase or lowercase characters. Trim(), TrimEnd(), and TrimStart() Removes spaces (or the characters you specify) from either end (or both ends) of a string. PadLeft() and PadRight() Adds the specified character to the appropriate side of a string as many times as necessary to make the total length of the string equal to the number you specify. For example, "Hi".PadLeft(5, '@') returns the string @@@Hi. Insert() Puts another string inside a string at a specified (zero-based) index position. For example, Insert(1, "pre") adds the string pre after the first character of the current string. Remove() Removes a specified number of characters from a specified position. For example, Remove(0, 1) removes the first character. Replace() Replaces a specified substring with another string. For example, Replace("a", "b") changes all a characters in a string into b characters. Substring() Extracts a portion of a string of the specified length at the specified location (as a new string). For example, Substring(0, 2) retrieves the first two characters. StartsWith() and EndsWith() Determines whether a string starts or ends with a specified substring. For example, StartsWith("pre") will return either true or false, depending on whether the string begins with the letters pre in lowercase. munotes.in

Page 31


31 The C# Language 2.7.2 The DateTime and TimeSpan Types  The DateTime and TimeSpan data types also have built-in methods and properties.  These class members allow you to perform three useful tasks:  Extract a part of a DateTime (for example, just the year) or convert a TimeSpan to a specific representation (such as the total number of days or total number of minutes).  Easily perform date calculations.  Determine the current date and time and other information (such as the day of the week or whether the date occurs in a leap year)  For example, the following block of code creates a DateTime object, sets it to the current date and time, and adds a number of days.  It then creates a string that indicates the year that the new date falls in (for example, 2012). DateTime myDate = Date Time.Now;
myDate = myDate.AddDays (100);
string dateString = myDate.Year.ToString();  The next example shows how you can use a TimeSpan object to find the total number of minutes between two DateTime objects: DateTime myDate1 = DateTime.Now;
DateTime myDate 2 = DateTime.Now.AddHours(3000);
TimeSpan difference;
diffe rence = myDate2.Subtract(myDate1 );
double numberOfMinutes;
numberOfMinutes = difference.TotalMinutes;  The DateTime and TimeSpan classes also support the + and – arithmetic operators, which do the same work as the built-in methods. That means you can rewrite the example shown earlier like this: munotes.in

Page 32


32 Advanced Web Programming
32 // Adding a TimeSpan to a DateTime creates a new DateTime.
DateTime myDate1 = DateTime.Now;
TimeSpan interval = TimeSpan.FromHours(3000);
DateTime myDate2 = myDate1 + interval;
// Subtractin g one DateTime object from another produces a
TimeSpan.
TimeSpan difference;
difference = myDate2 - myDate1; Now : Gets the current date and time. Today: Gets the current date and leaves time set to 00:00:00. Year, Date, Month, Hour, Minute, Second, and Millisecond Returns one part of the DateTime object as an integer. For example, Month will return 12 for any day in December. Add() and Subtract() Adds or subtracts a TimeSpan from the DateTime. For convenience, these operations are mapped to the + and – operators, so you can use them instead when performing calculations with dates. AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds(), AddMilliseconds() Adds an integer that represents a number of years, months, and so on, and returns a new DateTime. You can use a negative integer to perform a date subtraction. IsLeapYear() Returns true or false depending on whether the specified year is a leap year. ToString() Returns a string representation of the current DateTime object. You can also use an overloaded version of this method that allows you to specify a parameter with a format string. 2.7.3 The Array Type  Arrays also behave like objects in the world of .NET. (Technically, every array is an instance of the System.Array type.)  For example, if you want to find out the size of a one-dimensional array, you can use the Length property or the GetLength() method, both of which return the total number of elements in an array: int[] myArray = {1, 2, 3, 4, 5};
int numberOfElements;
numberOfElem ents = myArray.Length; // numberOfElements = 5 munotes.in

Page 33


33 The C# Language  You can also use the GetUpperBound() method to find the highest index number in an array. When calling GetUpperBound(), you supply a number that indicates what dimension you want to check.  In the case of a one-dimensional array, you must always specify 0 to get the index number from the first dimension.  In a two dimensional array, you can also use 1 for the second bound; in a three-dimensional array, you can also use 2 for the third bound; and so on. The fol lowing code snippet shows GetUpperBound() in action:
int[] myArray = {1, 2, 3, 4, 5};
int bound;
// Zero represents the first dimension of an array.
bound = myArray. GetUpper Bound(0); // bound = 4  On a one-dimensional array, GetUpperBound() always returns a number that’s one less than the length. That’s because the first index number is 0.  For example, the following code snippet uses GetUpperBound() to find the total number of rows and the total number of columns in a two-dimensional array: // Create a 4x2 array (a grid with four rows and two columns).
int[,] intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
int rows = intArray.GetUpperBound(0) + 1; // rows = 4
int columns = intArray.GetUpperBound(1) + 1; // columns = 2 Length Returns an integer that represents the total number of elements in all dimensions of an array. For example, a 3 × 3 array has a length of 9. GetLowerBound() and GetUpperBound() Determines the dimensions of an array. As with just about everything in.NET, you start counting at zero (which represents the first dimension). Clear() Empties part or all of an array’s contents, depending on the index values that you supply. The elements revert to their initial empty values (such as 0 for numbers). IndexOf () and LastIndexOf () Searches a one-dimensional array for a specified value and returns the index number. You cannot use this with multidimensional arrays. Sort() Sorts a one-dimensional array made up of comparable data such as strings or numbers. munotes.in

Page 34


34 Advanced Web Programming
34 Reverse () Reverses a one-dimensional array so that its elements are backward, from last to first. 2.8 CONDITIONAL LOGIC  Conditional logic means deciding which action to take based on user input, external conditions, or other information—is the heart of programming.  All conditional logic starts with a condition: a simple expression that can be evaluated to true or false.  Your code can then make a decision to execute different logic depending on the outcome of the condition.  To build a condition, you can use any combination of literal values or variables along with logical operators. Table below lists the basic logical operators.
 You can use all the comparison operators with any numeric types. With string data types, you can use only the equality operators (== and !=). C# doesn’t support other types of string comparison operators. int result;
result = String.Compare("apple", "attach"); // result = -1
result = String.Compare("apple", "all"); // result = 1
result = String.Compare("apple", "apple"); // result = 0
// An other way to perform string compa risons.
string word = "apple";
result = word.CompareTo("attach"); // result = -1 munotes.in

Page 35


35 The C# Language 2.8.1 Conditional Statements The if Statement  The if statement is the
powerhouse of conditional
logic, able to evaluate any
combination of c onditions
and deal with multiple and
different pieces of data.
 Here’s an example with an if
statement that features two
else conditions:
 An if block can have any
number of conditions. If you
test only a single condition,
you don’t need to include any
else blocks.
if (myNumber > 10)
{
// Do something.
}
else if (myString == "hello")
{
// Do something.
}
else
{
// Do something.
}  Keep in mind that the if construct matches one condition at most.  For example, if myNumber is greater than 10, the first condition will be met.  That means the code in the first conditional block will run, and no other conditions will be evaluated.  Whether my String contains the text hello becomes irrelevant, because that condition will not be evaluated. If you want to check both conditions, don’t use an else block—instead, you need two if blocks back-to-back, as shown here: if (myNumber > 10)
{
// Do something.
}
if (myString == "hello")
{
// Do something.
} The switch Statement  C# also provides a switch statement that you can use to evaluate a single variable or expression for multiple possible values. The only limitation is that the variable you’re evaluating must be an integer-based data type, a bool, a char, a string, or a value from an enumeration. Other data types aren’t supported. munotes.in

Page 36


36 Advanced Web Programming
36  In the following code, each case examines the myNumber variable and tests whether it’s equal to a specific integer: switch (myNumber)
{
case 1:
// Do something.
break;
case 2:
// Do something.
break;
default:
// Do something.
break;
}  You’ll notic e that the C# syntax
inherits the convention of C/C++
programming, which requires that
every branch in a switch statement be
ended by a special break keyword.
 If you omit this keyword, the
compiler will alert you and refuse to
build your application.
 The only exception is if you choose to
stack multiple case statements directly
on top of each other with no
intervening code.
 This allows you to write one segment
of code that handles more than one
case. Here’s an example:
switch (myNumber)
{
case 1:
case 2:
// This code executes if
myNu mber is 1 or 2.
break;
default:
// Do something.
break;
}  Unlike the if statement, the
switch statement is limited to
evaluating a single piece of
information at a time.
 However, it provides a
cleaner, clearer syntax than
the if statement when you
need to test a single variable.
2.8 LOOPS IN C# Introduction  Loops allow you to repeat a segment of code multiple times. C# has three basic types of loops. You choose the type of loop based on the type of task you need to perform. Your choices are as follows: munotes.in

Page 37


37 The C# Language  You can loop a set number of times with a for loop.  You can loop through all the items in a collection of data by using a foreach loop.  You can loop while a certain condition holds true with a while or do...while loop.  The for and foreach loops are ideal for chewing through sets of data that have known, fixed sizes.  The while loop is a more flexible construct that allows you to continue processing until a complex condition is met. The while loop is often used with repetitive tasks or calculations that don’t have a set number of iterations. 2.8.1 The for Loop  The for loop is a basic ingredient in many programs. It allows you to repeat a block of code a set number of times, using a built-in counter.  To create a for loop, you need to specify a starting value, an ending value, and the amount to increment with each pass. Here’s one example:  You’ll notice that the for loop starts with parentheses that indicate three important pieces of information. The first portion (int i = 0) creates the counter variable (i) and sets its initial value (0).  The third portion (i++) increments the counter variable. In this example, the counter is incremented by 1 after each pass.  That means i will be equal to 0 for the first pass, equal to 1 for the second pass, and so on. However, you could adjust this statement so that it decrements the counter (or performs any other operation you want). for (int i = 0; i < 10; i++)
{
// This code executes ten times.
System.Diagnostics.Debug.Write(i);
}
string[] stringArray = {"one", "two", "three"};
for (int i = 0; i < stringArray.Length; i++)
{
System.Diagnostics.Debug.Write(stringArray[i] + " "); }
munotes.in

Page 38


38 Advanced Web Programming
38  The middle portion (i < 10) specifies the condition that must be met for the loop to continue. This condition is tested at the start of every pass through the block. If i is greater than or equal to 10, the condition will evaluate to false, and the loop will end. 2.8.2 The foreach Loop  C# also provides a foreach loop that allows you to loop through the items in a set of data.  With a foreach loop, you don’t need to create an explicit counter variable.  Instead, you create a variable that represents the type of data for which you’re looking. Your code will then loop until you’ve had a chance to process each piece of data in the set.  The foreach loop is particularly useful for traversing the data in collections and arrays.  For example, the next code segment loops through the items in an array by using foreach.
 This code has exactly the same effect as the example in the previous section, but it’s a little simpler:  In this case, the foreach loop examines each item in the array and tries to convert it to a string. Thus, the foreach loop defines a string variable named element.  If you used a different data type, you’d receive an error.  The foreach loop has one key limitation: it’s read-only.  For example, if you wanted to loop through an array and change the values in that array at the same time, foreach code wouldn’t work. string[] stringArray = {"one", "two", "three"};
foreach (string element in stringArray)
{
// This code loops three times, with the element variable set
to
// "one", t hen "two", and then "three".
System.Diagnostics.Debug.Write(element + " ");
} munotes.in

Page 39


39 The C# Language
 Here’s an example of some flawed code: 2.8.3 The While Loop  Finally, C# supports a while loop that tests a specific condition before or after each pass through the loop.  When this condition evaluates to false, the loop is exited. Here’s an example that loops ten times.  At the beginning of each pass, the code evaluates whether the counter (i) is less than some upper limit (in this case, 10). If it is, the loop performs iteration.
 You can also place the condition at the end of the loop by using the do...while syntax. In this case, the condition is tested at the end of each pass through the loop:
int i = 0;
while (i < 10)
{
i += 1;
// This code executes ten times. } int i = 0;
do
{
i += 1;
// This co de executes ten times.
}
while (i < 10); int[] intAr ray = {1,2,3};
foreach (int num in intArray)
{
num += 1;
} munotes.in

Page 40


40 Advanced Web Programming
40 2.9 METHODS IN C#  Methods are the most basic building block you can use to organize your code.  Essentially, a method is a named grouping of one or more lines of code.  Ideally, each method will perform a distinct, logical task.  By breaking down your code into methods, you not only simplify your life, but also make it easier to organize your code into classes and step into the world of object-oriented programming.  When you declare a method in C#, the first part of the declaration specifies the data type of the return value, and the second part indicates the method name.  If your method doesn’t return any information, you should use the void keyword instead of a data type at the beginning of the declaration.
 Notice that the method name is always followed by parentheses. This allows the compiler to recognize that it’s a method.  In this example, the methods don’t specify their accessibility. This is just a common C# convention. You’re free to add an accessibility keyword (such as public or private), as shown here: // This method doesn’t return any information.
void MyMethodNoReturnedData()
{
// Code goes here.
}
// This method returns an integer.
int MyMethodRetu rnsData()
{
// As an example, return the number 10.
return 10;
} munotes.in

Page 41


41 The C# Language  The accessibility determines how different classes in your code can interact.  Private methods are hidden from view and are available only locally, whereas public methods can be called by all the other classes in your application.  To really understand what this means, you’ll need to read the next chapter, which discusses accessibility in more detail.  Invoking your methods is straightforward—you simply type the name of the method, followed by parentheses.  If your method returns data, you have the option of using the data it returns or just ignoring it:
2.9.1 Parameters  Methods can also accept information through parameters. Parameters are declared in a similar way to variables.  By convention, parameter names always begin with a lowercase letter in any language. private void MyMethodNoReturnedData()
{
// Code goes here.
}
// This call is allowed.
MyMe thodNoReturnedData();
// This call is allowed.
MyMethodReturnsData();
// This call is allowed.
int myNumber;
myNumber = MyMethodReturnsData();
// This call isn’t allowed.
// MyMethodNoReturnedData() does not return any
information.
myNumber = MyMethodN oRet urnedData(); munotes.in

Page 42


42 Advanced Web Programming
42  Here’s how you might create a function that accepts two parameters and returns their sum:
 When calling a method, you specify any required parameters in parentheses or use an empty set of parentheses if no parameters are required:
2.9.2 Method Overloading  C# supports method overloading, which allows you to create more than one method with the same name but with a different set of parameters.  When you call the method, the CLR automatically chooses the correct version by examining the parameters you supply.  This technique allows you to collect different versions of several methods together.  For example, you might allow a database search that returns an array of Product objects representing records in the database.  Rather than create three methods with different names depending on the criteria, such as GetAllProducts(), GetProductsInCategory(), and GetActiveProducts(), you could create three versions of the GetProducts() method.  Each method would have the same name but a different signature, meaning it would require different parameters.  This example provides two overloaded versions for the GetProductPrice() method: private int AddNumbers(int number1, int number2)
{
return number1 + number2;
} // Ca ll a method with no parameters.
MyMethodNoReturnedData();
// Ca ll a method that requires two integer parameters.
MyMethodNoReturnedData2(10, 20);
// Call a method with two integer parameters and an
integer return value.
int returnValue = AddNumbers(10, 10) ; munotes.in

Page 43


43 The C# Language
 Now you can look up product prices based on the unique product ID or the full product name, depending on whether you supply an integer or string argument:
 You cannot overload a method with versions that have the same signature that is, the same number of parameters and parameter data types because the CLR will not be able to distinguish them from each other.  When you call an overloaded method, the version that matches the parameter list you supply is used. If no version matches, an error occurs. Optional and Named Parameters  Method overloading is a time-honored technique for making methods more flexible, so you can call them in a variety of ways.  C# also has another feature that supports the same goal: optional parameters.  An optional parameter is any parameter that has a default value.  If your method has normal parameters and optional parameters, the optional parameters must be placed at the end of the parameter list.  Here’s an example of a method that has a single optional parameter: private decimal GetProductPrice(int ID)
{
// Code here.
}
private de cimal GetProductPrice(string name)
{
// Code here.
}
// And so on... decimal price;
// Get price by product ID (the first version ).
price = GetProductPrice(1001);
// Get price by product name (the second version).
price = GetProductPrice("DVD Player"); munotes.in

Page 44


44 Advanced Web Programming
44 2.11 DELEGATES  Delegates allow you to create a variable that “points” to a method. You can then use this variable at any time to invoke the method.  Delegates help you write flexible code that can be reused in many situations.  They’re also the basis for events, an important .NET concept that you’ll consider in the next chapter.  The first step when using a delegate is to define its signature.  The signature is a combination of several pieces of information about a method: its return type, the number of parameters it has, and the data type of each parameter.
 A delegate variable can point only to a method that matches its specific signature.  In other words, the method must have the same return type, the same number of parameters, and the same data type for each parameter as the delegate.  For example, if you have a method that accepts a single string parameter and another method that accepts two string parameters, you’ll need to use a separate delegate type for each method.  To consider how this works in practice, assume that your program has the following method: private string GetUserName(int ID, bool useShortForm = false)
{
// Code here.
}
// Expl icitly set the useShortForm parameter.
name = GetUserName(401, true);
// Don't set the useShortForm parameter, and use the default
value (false).
name = GetUserNa me(401);
private string TranslateEnglishToFrench(string english)
{
// Code goes here.
} munotes.in

Page 45


45 The C# Language  This method accepts a single string argument and returns a string.  With those two details in mind, you can define a delegate that matches this signature. Here’s how you would do it:  Notice that the name you choose for the parameters and the name of the delegate don’t matter.  The only requirement is that the data types for the return value and parameters match exactly.  Once you’ve defined a type of delegate, you can create and assign a delegate variable at any time. Using the String Function delegate type, you could create a delegate variable like this:  Using your delegate variable, you can point to any method that has the matching signature. In this example, the StringFunction delegate type requires one string parameter and returns a string. Thus, you can use the functionReference variable to store a reference to the TranslateEnglishToFrench() method  Now that you have a delegate variable that references a method, you can invoke the method through the delegate. To do this, you just use the delegate name as though it were the method name:  In the previous code example, the method that the function Reference delegate points to will be invoked with the parameter value "Hello", and the return value will be stored in the French String variable.  The following code shows all these steps—creating a delegate variable, assigning a method, and calling the method—from start to finish: 2.12 SUMMARY: This chapter 2 gives the basic syntax of OOP in C#. It discusses about class, methods, constructors, destructor, method overloading and few example programs. After learning the above topics, you can write many useful programs and built a strong foundation for larger programming projects. private delegate string StringFunction(string inputString);
StringFunction functionReference;
functi onReference = TranslateEnglishToFrench; string frenchString;
frenchString = functi onReference("Hello"); munotes.in

Page 46


46 Advanced Web Programming
46 2.13 QUESTIONS 1) Explain OOP in C#. 2) Explain class and its member in C#. 3) Explain the methods in C#. 4) Explain constructor with example in C#. 5) Explain method overloading with example in C#. 6) Explain properties and indexer in C#? 7) Explain inheritance with example. 8) Explain method overriding with example. 9) Explain abstract class. 10) Explain Interface with example. 11) Explain structure with example. 2.14 REFERENCES: 1) The Complete Reference: C# 2) Visual C# 2012: How to program. 3) https://docs.microsoft.com/en-us/dotnet/csharp/  munotes.in

Page 47

47 3 TYPES, OBJECTS, AND NAMESPACES Unit Structure 3.0 Types, Objects, and Namespaces 3.1 Introduction 3.2 The Basics about Classes 3.2.1 Objects in C# 3.2.2 Constructors 3.2.3 Destructors 3.3 Building a Basic Class 3.3.1 Static Data Members and Member Functions 3.3.2 this Object in C# 3.3.3 Access Specifier 3.3.4 Adding Properties in Class 3.4 Value Types and Reference Types 3.5 Understanding Namespaces and Assemblies 3.5.1 using Keyword 3.5.2 Nested Namespace 3.5.3 Assemblies in C# 3.6 Advanced Class Programming 3.6.1 Inheritance in C# 3.6.2 Interfaces in C# 3.6.3 Delegates in C# 3.7 Summary 3.8 Questions 3.9 References 3.1 INTRODUCTION  In this chapter, you’ll learn how objects are defined and how you manipulate them in your code. Taken together, these concepts are the basics of what’s commonly called object-oriented programming.  This chapter explains objects from the point of view of the .NET Framework.  It doesn’t rehash the typical object-oriented theory, because countless excellent programming books cover the subject. Instead, you’ll see the types of objects .NET allows, how they are constructed, and how they fit into the larger framework of namespaces and assemblies. munotes.in

Page 48


48 Advanced Web Programming
48 3.2 THE BASICS ABOUT CLASSES  Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities.  A class is a user-defined blueprint or prototype from which objects are created.  Basically, a class combines the fields and methods (member function which defines actions) into a single unit.  In C#, classes support polymorphism, inheritance and also provide the concept of derived classes and base classes.  Generally, a class declaration contains only keyword class, followed by an identifier(name) of the class.  But there are some optional attributes that can be used with class declaration according to the application requirement.  In general, class declarations can include these components, in order: Modifiers: A class can be public or internal etc. By default modifier of class is internal. Keyword class: A class keyword is used to declare the type class. Class Identifier: The variable of type class is provided. The identifier(or name of class) should begin with an initial letter which should be capitalized by convention. Base class or Super class: The name of the class’s parent (superclass), if any, preceded by the : (colon). This is optional. Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the : (colon). A class can implement more than one interface. This is optional. Body: The class body is surrounded by { } (curly braces). Note:
Constructors in class are used for initializing new objects.
Fields are variables that provide the state of the class and its
objects, and methods are used to implement the behavior of
the class and its objects. Syntax :
//[access modifier] - [class] - [identifier]
public clas s Custom er
{
// Fields, properties, met hods and events go here...
} munotes.in

Page 49


49 Types, Objects, And
Namespaces 3.2.1 Objects in C#  It is a basic unit of Object-Oriented Programming and represents the real-life entities.  A typical C# program creates many objects, which as you know, interact by invoking methods. An object consists of : State: It is represented by attributes of an object. It also reflects the properties of an object. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects. Identity: It gives a unique name to an object and enables one object to interact with other objects. Consider Dog as an object and see the below diagram for its identity, state, and behavior.  Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”.  An online shopping system might have objects such as “shopping cart”, “customer”, and “product”.  Declaring Objects (Also called instantiating a class)  When an object of a class is created, the class is said to be instantiated.  All the instances share the attributes and the behaviour of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.

munotes.in

Page 50


50 Advanced Web Programming
50 Syntax: Example 1: using System;
public class Student
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void Main(string[] args)
{
Student s1 = new Student();//creating an object of Student
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
} } Example 2: Initialize and Display data through method using System;
public class Student
{
public int id;
public String name;
public void insert(int i, String n)
{
id = i;
name = n;
}
public voi d display()
{
Console.WriteLine(id + " " + name);
}
}
class TestStudent{ Classname objectname = new classname(); munotes.in

Page 51


51 Types, Objects, And
Namespaces public static void Main(string[] args)
{
Student s1 = new Student( );
Student s2 = new Studen t();
s1.insert(101, "Ajeet");
s2.insert(102, "Tom");
s1.display();
s2.display();
} } 3.2.2 Constructors  Constructors are methods that are called when the object is first created. To create an object, the constructor call is preceded by the keyword “new”.  The process of doing this is called instantiation.  An object is then referred to as an instance of its class. They are often used to initialize the data of an object.  A constructor has the same name as the name of its type (name of class).  Its method signature includes only the method name and its parameter list; it does not include a return type.  Objects are allocated on the heap (a memory region allocated for the program).  Objects must be created with new Eg. Stack stk = new Stack(50);  If you don't provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values.  If a constructor was declared, no default constructor is generated. How constructors are different from a normal member function?  A constructor is different from normal functions in following ways:  Constructor has same name as the class itself  Constructors don’t have return type  A constructor is automatically called when an object is created.  It must be placed in public section of class.  If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body). munotes.in

Page 52


52 Advanced Web Programming
52 In C#, constructors can be divided into 5 types 1) Default Constructor 2) Parameterized Constructor 3) Copy Constructor 4) Static Constructor 5) Private Constructor 1) Default Constructor in C#  A constructor without any parameters is called a default constructor; in other words, this type of constructor does not take parameters.  The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class with different values.  The default constructor initializes: All numeric fields in the class to zero. All string and object fields to null. using System;
namespace DefaultConstru ctor
{
class addition
{
int a, b;
public addition() //d efault con structor
{
a = 100;
b = 175;
}
public static void Main()
{
addition obj = new addition(); //an object is created ,
constructor is called
Console.WriteLine(obj.a);
Console.WriteLine(obj.b);
Console.Read();
}
}
} munotes.in

Page 53


53 Types, Objects, And
Namespaces 2) Parameterized Constructor in C#  A constructor with at least one parameter is called a parameterized constructor.  The advantage of a parameterized constructor is that you can initialize each instance of the class with a different value. using System;
namespace Constructor
{
class paraconstrctor
{
public int a, b;
public parac onstrctor(int x, int y) // declaring Para meterized
Constructor with int x, y parameter
{
a = x;
b = y;
}
}
class MainClass
{
static void Main()
{
paraconstrctor v = new paraconstrctor(100, 175); // Creating
object of P arameterized Constructor and int values
Console.WriteLine(" ----------- parameterized constructor
example by vithal wadje --------------- ");
Console.WriteLine(" \t");
Console.WriteLine("value of a=" + v.a );
Console.WriteLine("value of b=" + v.b);
Console.Read();
}
}
} munotes.in

Page 54


54 Advanced Web Programming
54 3) Copy Constructor in C#  The constructor which creates an object by copying variables from another object is called a copy constructor.  The purpose of a copy constructor is to initialize a new instance to the values of an existing instance. publi c employee(employee emp)
{
name=emp.name;
age=emp.age;
} The copy constructor is invoked by instantiating an object of type employee and bypassing it the object to be copied. Example employee emp1=new emplo yee (emp2); using System;
namespace co pyConstru ctor
{
class employee
{
private string name;
private int age;
public employee(employee emp) // declaring Copy constructor.
{
name = emp.name;
age = emp.age;
}
public employee(string name, int age) // Instance constructor.
{
this.name = name;
this.age = age;
}
publ ic string Details // Get de tails of employee
{ munotes.in

Page 55


55 Types, Objects, And
Namespaces get
{
return " The age of " + name +" is "+ age.ToString();
}
}
}
class empdetail
{
static void Main()
{
employee emp1 = new employee("Vithal", 23); // Create a ne w
employee object.
employee emp2 = new employee(emp1); // here is emp1
details is copied to emp2.
Console.WriteLine(emp2.Details);
Console.ReadLine();
}
}} 4) Static Constructor in C#  When a constructor is created using a static keyword, it will be invoked only once for all of the instances of the class and it is invoked during the creation of the first instance of the class or the first reference to a static member in the class.  A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once. Some key points of a static constructor are:  A static constructor does not take access modifiers or have parameters.  A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.  A static constructor cannot be called directly.  The user has no control over when the static constructor is executed in the program.  A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. munotes.in

Page 56


56 Advanced Web Programming
56 using System;
namespace staticConstru ctor
{
public class employee
{
static employee() // Static constructor
declaration{Console.WriteLine("The st atic constructor ");
}
public static void Salary()
{
Console.WriteLine();
Console.WriteLine("The Salary method");
}
}
class details
{
static void Main()
{
Console.Writ eLine(" ---------- Static constr uctor examp le by vithal
wadje ---------- ");
Console.WriteLine();
employee.Salary();
Console.ReadLine();
}
}
} 5) Private Constructor in C#  When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class.  They are usually used in classes that contain static members only. Some key points of a private constructor are:  One use of a private constructor is when we have only static members.  It provides an implementation of a singleton class pattern munotes.in

Page 57


57 Types, Objects, And
Namespaces  Once we provide a constructor that is either private or public or any, the compiler will not add the parameter-less public constructor to the class. using System;
namespace defaultConstr uctor
{
public class Counter
{
private Counter() //private constr uctor declaration
{
}
public static int currentV iew;
public static int visitedCount()
{
return ++ currentV iew;
}
}
class viewCountedetails
{
static void Main()
{
// Counter aCounter = new Counter(); // Error
Console.WriteLine(" ------- Private constructor example by
vithal wa dje---------- ");
Console.Writ eLine();
Counter.currentV iew = 500;
Counter.visitedCount();
Console.WriteLine("Now the view count is: {0}",
Counter.currentV iew);
Console.ReadLine();
}
}
} munotes.in

Page 58


58 Advanced Web Programming
58 3.2.3 Destructors  Destructors in C# are methods inside the class used to destroy instances of that class when they are no longer needed.  The Destructor is called implicitly by the .NET Framework’s Garbage collector and therefore programmer has no control as when to invoke the destructor.  An instance variable or an object is eligible for destruction when it is no longer reachable. Important Points:  A Destructor is unique to its class i.e. there cannot be more than one destructor in a class.  A Destructor has no return type and has exactly the same name as the class name (Including the same case).  It is distinguished apart from a constructor because of the Tilde symbol (~) prefixed to its name.  A Destructor does not accept any parameters and modifiers.  It cannot be defined in Structures. It is only used with classes.  It cannot be overloaded or inherited.  It is called when the program exits.  Internally, Destructor called the Finalize method on the base class of object.
3.2.4 Static Data Members and Member Functions class Example
{
// Rest of the class
// members and methods.

// Destructor
~Example()
{
// Your code
}
}
munotes.in

Page 59


59 Types, Objects, And
Namespaces  We can define class members as static using the static keyword.  When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.  The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.  Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition. using System;
namespace StaticVarApplication {
class StaticVar {
public static int num;

public void count() {
num++;
}
public int ge tNum() {
return num;
}
}
class StaticTester {
static void Main(string[] args) {
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.R eadKey();
}
}
} munotes.in

Page 60


60 Advanced Web Programming
60 Static Method  A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level.  That means, all instances of the class share the same copy of the method and its data. The last updated value of the method is shared among all objects of that Type.  Static methods are called by using the class name, not the instance of the class. class StaticDemo
{
public static void withoutObj()
{
Console.WriteLine("Hello");
}
static void Main()
{
Program. withoutObj();
Console.ReadKey();
}
} Using Static Method  Usually we define a set of data members for a class and then every object of that class will have a separate copy of each of those data members. class Program
{
public int myVar; //a non -static field
static void Main()
{
StaticDemo p1 = new StaticDemo(); //a n object of class
p1.myVar = 10;
p1.withoutObj();
Console.WriteLine(p1.myVar);
Console.ReadKey();
}
} munotes.in

Page 61


61 Types, Objects, And
Namespaces 3.3.2 this Object in C#  The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name.  Another usage of “this” keyword is to call another constructor from a constructor in the same class.  Here, for an example, we are showing a record of Students i.e: id, Name, Age, and Subject. To refer to the fields of the current class, we have used the “this” keyword in C#. public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
} using System.IO;
using System;

class Student {
public int id, age;
public String name, subject;

public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
}
public void sho wInfo() {
Console.WriteLine(id + " " + name+" "+age+ " "+subject);
}
}

class StudentDetails {
public static void Main(string[] args) {
Student std1 = new Student(001, "Jack", 23, "Maths"); munotes.in

Page 62


62 Advanced Web Programming
62 Student std2 = new Student(002, "Harry", 2 7, "Science");
Student std3 = new S tudent(003, "Steve", 23,
"Programming");
Student std4 = new Student(004, "David", 27, "English");

std1.showInfo();
std2.showInfo();
std3.showInfo();
std4.showInfo();
}
} 3.3.3 Access Specifier
3.3.4 Adding Properties in Class  Property in C# is a member of a class that provides a flexible mechanism for classes to expose private fields. Internally, C# properties are special methods called accessors.  A C# property have two accessors, get property accessor and set property accessor.  A get accessor returns a property value, and a set accessor assigns a new value. The value keyword represents the value of a property.  Properties in C# and .NET have various access levels that is defined by an access modifier.  Properties can be read-write, read-only, or write-only. The read-write property implements both, a get and a set accessor.  A write-only property implements a set accessor, but no get accessor. A read-only property implements a get accessor, but no set accessor. munotes.in

Page 63


63 Types, Objects, And
Namespaces class Pers on
{
private string name; // field

public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
} Example: class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}

class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
} 3.4 VALUE TYPES AND REFERENCE TYPES  In C#, these data types are categorized based on how they store their value in the memory. C# includes the following categories of data types:  Value type  Reference type munotes.in

Page 64


64 Advanced Web Programming
64 Value Type  A data type is a value type if it holds a data value within its own memory space. It means the variables of these data types directly contain values.  For example, consider integer variable int i = 100;  The system stores 100 in the memory space allocated for the variable i.  The following image illustrates how 100 is stored at some hypothetical location in the memory (0x239110) for 'i':
The following data types are all of value type:  bool  byte  char  decimal  double  enum  float  int  long etc. Passing Value Type Variables  When you pass a value-type variable from one method to another, the system creates a separate copy of a variable in another method.  If value got changed in the one method, it wouldn't affect the variable in another method static void ChangeValue(int x)
{
x = 200;
Console.W riteLine(x);
}
static void Main(string[] args)
{
int i = 100;
Console.WriteLine(i);
ChangeValue(i);
Console.WriteLine(i);
} munotes.in

Page 65


65 Types, Objects, And
Namespaces Reference Type  Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored.  In other words, a reference type contains a pointer to another memory location that holds the data.  For example, consider the following string variable: string s = "Hello World!!";  The following image shows how the system allocates the memory for the above string variable.
 As you can see in the above image, the system selects a random location in memory (0x803200) for the variable s.  The value of a variable s is 0x600000, which is the memory address of the actual data value.  Thus, reference type stores the address of the location where the actual value is stored instead of the value itself. The followings are reference type data types: String Arrays (even if their elements are value types) Class Delegate Passing Reference Type Variables  When you pass a reference type variable from one method to another, it doesn't create a new copy; instead, it passes the variable's address.  So, If we change the value of a variable in a method, it will also be reflected in the calling method. munotes.in

Page 66


66 Advanced Web Programming
66 static void ChangeReferenceType (Student std2)
{
std2.StudentName = "Steve";
}
static void Main(string[] args)
{
Student std1 = new Student();
std1.StudentName = "Bill";
ChangeReferenceType(std1);
Console.WriteLine(std1.Student Name);
} 3.5 UNDERSTANDING NAMESPACES AND ASSEMBLIES Namespaces in C#  Namespaces are used to organize the classes.  It helps to control the scope of methods and classes in larger .Net programming projects.  The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace.  It is also referred as named group of classes having common features.  The members of a namespace can be namespaces, interfaces, structures, and delegates.  There are two types of namespaces. 1. User Defined Namespace 2. Build in Namespaces. Defining a User-Defined Namespace  To define a namespace in C#, we will use the namespace keyword followed by the name of the namespace and curly braces containing the body of the namespace as follows: Example:
// defining the namespace name1
namespace name1
{
// C1 is the class in the namespace name1
class C1
{
// class code
}
} munotes.in

Page 67


67 Types, Objects, And
Namespaces using System;
namespace first_space {
class name space_cl {
public void func() {
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space {
class namespace_cl {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
class TestC lass {
static void Main(string[] args) {
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new
second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}

When th e above code is compiled and executed, it produces the
following result -
Inside first_space
Inside second_space 3.5.1 The Using Keyword  The using keyword states that the program is using the names in the given namespace. For example, we are using the System namespace in our programs. The class Console is defined there. We just write - Console.WriteLine ("Hello there"); We could have written the fully qualified name as - System.Console.WriteLine("Hello there");  You can also avoid prepending of namespaces with the using namespace directive. munotes.in

Page 68


68 Advanced Web Programming
68  This directive tells the compiler that the subsequent code is making use of names in the specified namespace.  The namespace is thus implied for the following code – using System;
using first_space;
using second_space;

namespace first_space {
class abc {
public void func() {
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space {
class efg {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
class TestClass {
static voi d Main(string[] args) {
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the
following r esult -

Inside first_space
Inside second _space munotes.in

Page 69


69 Types, Objects, And
Namespaces 3.5.2 Nested Namespace You can define one namespace inside another namespace as follows - namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } } using System;
using first_space;
using fi rst_space.second_space;
namespace first_space {
class abc {
public void func() {
Console.WriteLine("Inside first_space");
}
}
namespace second_space {
class efg {
public void func() {
Console.WriteLi ne("Inside second_space");
}
}
}
}
class TestClass {
static void Main(string[] args) {
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.Read Key();
}
}
When the above code is comp iled and executed, it produces the following
result -
Inside first_space
Inside second_space munotes.in

Page 70


70 Advanced Web Programming
70 3.5.3 Assemblies in C#  An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.  Assemblies take the form of executable (.exe) or dynamic link library (. dll) files, and are the building blocks of .NET applications.  An Assembly is a basic building block of .Net Framework applications. It is basically a compiled code that can be executed by the CLR.  An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An Assembly can be a DLL or exe depending upon the project that we choose. Assemblies have the following properties:  Assemblies are implemented as .exe or .dll files.  For libraries that target the .NET Framework, you can share assemblies between applications by putting them in the global assembly cache (GAC). You must declare strong-name assemblies before you can include them in the GAC.  Assemblies are only loaded into memory if they are required. If they aren't used, they aren't loaded. This means that assemblies can be an efficient way to manage resources in larger projects. Assemblies are basically the following two types: 1. Private Assembly 2. Shared Assembly 1. Private Assembly  It is an assembly that is being used by a single application only.  Suppose we have a project in which we refer to a DLL so when we build that project that DLL will be copied to the bin folder of our project.  That DLL becomes a private assembly within our project. Generally, the DLLs that are meant for a specific project are private assemblies. 2. Shared Assembly  Assemblies that can be used in more than one project are known to be a shared assembly.  Shared assemblies are generally installed in the GAC.  Assemblies that are installed in the GAC are made available to all the .Net applications on that machine. GAC(Global Assembly Cache)  GAC stands for Global Assembly Cache. It is a memory that is used to store the assemblies that are meant to be used by various applications.  Every computer that has CLR installed must have a GAC. GAC is a location that can be seen at “C:\Windows\assembly” for .Net munotes.in

Page 71


71 Types, Objects, And
Namespaces applications with frameworks up to 3.5. For higher frameworks like 4 and 4.5 the GAC can be seen at: “C:\Windows\Microsoft.NET\assembly\GAC_MSIL”. Components of Assembly: A static assembly consist of 4 elements:- 1. The assembly manifest, which contains assembly metadata. 2. Type metadata 3. Microsoft Intermediate Language(MSIL) code that implement the type. 4. A set of resources. Assembly manifest :-  Every assembly whether static or dynamic contain a collection of data that describes how the element in assembly relates to each other.  It contains its assembly metadata such as assembly version requirement & security identity & all metadata needed to define this scope of the assembly & resolve references to resources & classes.  It can be stored in either PE file(portable exe file) or .dll file with Microsoft intermediate language(MSIL) code or in a standalone PE file that contains only assembly manifest information. The following illustration show the different ways to manifest can be stored.
The following table shows the information contain in the assembly manifest. Information Description Assembly
name A text string specifying the assembly name. Version
number A major & minor version number & a revision & build
number. The common lang uage runtime uses this no. to
enforce version policy. munotes.in

Page 72


72 Advanced Web Programming
72 Culture Information on the culture or la nguage th e assembly
supports the informat ion should be use d only to
designate an assembly as a satellite assembly
containing culture or language specific information. Strong name
Information The public key from the publisher if the assembly has
been given a strong name. 3.6 ADVANCED CLASS PROGRAMMING  Part of the art of object-oriented programming is determining object relations.  For example, you could create a Product object that contains a ProductFamily object or a Car object that contains four Wheel objects.  To create this sort of object relationship, all you need to do is define the appropriate variable or properties in the class. This type of relationship is called containment (or aggregation). 3.6.1 Inheritance in C#  One of the most important concepts in object-oriented programming is inheritance.  Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application.  This also provides an opportunity to reuse the code functionality and speeds up implementation time.  The process of creating new class from an existing class is called as inheritance.  When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class.  This existing class is called the base class, and the new class is referred to as the derived class. class {
...
}

class : {
...
} munotes.in

Page 73


73 Types, Objects, And
Namespaces Types of Inheritance
OOPs support the six different types of inheritance as given below : 1. Single inheritance 2. Multi-level inheritance 3. Multiple inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance Single inheritance  In this inheritance, a derived class is created from a single base class.  In the given example, Class A is the parent class and Class B is the child class since Class B inherits the features and behavior of the parent class A. Multi-level inheritance  In this inheritance, a derived class is created from another derived class.  In the given example, class c inherits the properties and behavior of class B and class B inherits the properties and behavior of class B. So, here A is the parent class of B and munotes.in

Page 74


74 Advanced Web Programming
74  class B is the parent class of C. So, here class C implicitly inherits the properties and behavior of class A along with Class B i.e there is a multilevel of inheritance. Multiple inheritance  In this inheritance, a derived class is created from more than one base class. This inheritance is not supported by .NET Languages like C#, F# etc. and Java Language.  In the given example, class c inherits the properties and behavior of class B and class A at same level. So, here A and Class B both are the parent classes for Class C. Hierarchical Inheritance  In this inheritance, more than one derived classes are created from a single base class and further child classes act as parent classes for more than one child classes.  In the given example, class A has two children class B and class D. Further, class B and class C both are having two children - class D and E; class F and G respectively. Hybrid inheritance  This is combination of more than one inheritance. Hence, it may be a combination of Multilevel and Multiple inheritance or Hierarchical etc.  Example Of Multilevel Inheritance using System;
class A
{
public void displa yA()
{
Console.WriteLine("Base Class Function");
}
}
class B : A
{
public void displayB()
{
Console.WriteLine("Derived Class Function");
}
} munotes.in

Page 75


75 Types, Objects, And
Namespaces class C : B
{
public void displayC()
{
Console.WriteLine("Derived Class Function");
}
}
class Programs
{
public static void Main(string[] a rgs)
{
C obj = new C();
obj.displa yA();
obj.displayB();
obj.displayC();
Console.ReadKey();
}
} Hierarchical Inheritance using System;
class A
{
public void displa yA()
{
Console.WriteLine("Ba se Class Function");
}
}
class B : A
{
public void displayB()
{
Console.WriteLine("Derived Class Function");
}
}
class C : A munotes.in

Page 76


76 Advanced Web Programming
76 {
public void displayC()
{
Console.WriteLine("Derived Class Function");
}
}
class Progr ams
{
public static void Main(strin g[] args)
{

B obj1 = new B();
C obj = new C();

obj.displa yA();
obj.displayC();

obj1.displa yA();
obj1.displayB();
Console.ReadKey();
}
} 3.6.2 Interfaces in C#  Interface is like a contract. In the human world, the contract between the two or more humans binds them to act as per the contract.  In the same way, the interface includes the declaration of one or more functionalities.  Entities that implement the interface must define functionalities declared in the interface. In C#, a class or a struct can implement one or more interfaces  In C# an interface can be defined using the interface keyword.  Interfaces can contain methods, properties, indexers, and events as members.  You cannot use any access modifier for any member of an interface. All the members by default are public members. munotes.in

Page 77


77 Types, Objects, And
Namespaces Implementing an Interface A class or a Struct can implement one or more interfaces using colon (:). Syntax: : using Syste m;
interface MyInterface
{
void display();
}
class CallInterface : MyInterface
{
public void display()
{
Console.WriteLine("Interface is called");
}
}
class CallInterface1 : MyInterface
{
publ ic void display()
{
Cons ole.WriteLine("Interface Method");
}
}
class Programs
{
public static void Main(string[] args)
{
CallInterface obj = new CallInterface();
CallInterface1 obj1 = new CallInterface1();

obj.display();
obj1.display() ;

Console.ReadKey();
}
} munotes.in

Page 78


78 Advanced Web Programming
78 using System;
interface Addition
{
void add(int n1, int n2);
}
interface Subtraction
{
void sub(int n1, int n2);
}
class CallInterface : Addition,Subtraction
{
public void add(int n1, int n2)
{
Console.WriteLine("Addition :" + (n1 + n2));
}
public void sub(int n1, int n2)
{
Console.WriteLine("Subtraction :" + (n1 - n2));
}
}
class Programs
{
public static void Main(stri ng[] args)
{
CallInterface o bj = new CallInterface();

obj.add(10,10);
obj.sub(100,10);
Console.ReadKey();
}
} Explicit Interface Implementation  Explicit implementation is useful when class is implementing multiple interface thereby it is more readable and eliminates the confusion.  It is also useful if interfaces have same method name coincidently. munotes.in

Page 79


79 Types, Objects, And
Namespaces using System;
interface I1
{
void show();
}
interface I2
{
void show();
}
class CallInterface : I1,I2
{
void I1 .show()
{
Console.Writ eLine("I1 interface Method");
}
void I2.show()
{
Console.WriteLine("I2 Interface Method");
}
}
class Programs
{
public static void Main(string[] args)
{
CallInterface obj = ne w CallI nterface();
I1 i1 = (I1) o bj;
i1.show();
I2 i2 = (I2)obj;
i2.show();
Console.ReadKey();
}
} 3.6.3 Delegates in C#  A function can have one or more parameters of different data types, but what if you want to pass a function itself as a parameter?  How does C# handle the callback functions or event handler? The answer is - delegate. munotes.in

Page 80


80 Advanced Web Programming
80  Delegate is like a pointer to a function.  It is a reference type data type and it holds the reference of a method.  All the delegates are implicitly derived from System.Delegate class.  A delegate can be declared using delegate keyword followed by a function signature as shown below. delegate(); Steps to used Delegate 1) Declaration of delegate delegate ({
public void display()
{
Console.WriteLine("Delegate is called");
}
} 3) Delegate Instantiation(delegate object creation) DelegateMethod dm = new DelegateMethod(); MyDelegate d = new MyDelegate(dm.display); 4) Calling Delegate d(); Example
using System;
public delegate void MyDelegate(); // Step1
class DelegateMethod
{
public void display()
{
Console.WriteLine("Delegate is called");
}
} munotes.in

Page 81


81 Types, Objects, And
Namespaces class Programs
{
public static void Main(string[] args)
{

DelegateMethod dm = new DelegateMethod();
MyDelegate d = new MyDelegate(dm.display);

d();

Console.ReadKey() ;
}
} Types of Delegate 1) Simple Delegate  When delegate uses only one method to execute on the behalf of the delegate then it is called as simple delegate. 2) Multicast Delegate  The delegate can points to multiple methods. A delegate that points multiple methods is called a multicast delegate.  The "+" operator adds a function to the delegate object and the "-" operator removes an existing function from a delegate object. using System;
public delegate void Math Optr(in t n1, int n2);
class DelegateMetho d
{
public void add(int n1, int n2)
{
Console.WriteLine("Addition =" + (n1 + n2));
}
public void sub(int n1, int n2)
{
Console.WriteLine("Subtraction =" + (n1 - n2));
}
public vo id mult(int n1, int n2)
{
Console.WriteLine("Mult =" + (n1 * n2)); munotes.in

Page 82


82 Advanced Web Programming
82 }
public void div(int n1, int n2)
{
Console.WriteLine("Div =" + (n1 / n2));
}
}
class Programs
{
public static void Main(string[] args)
{

DelegateMethod dm = new Delegate Method();

MathOptr d1 = new MathOptr(dm.add);
MathOptr d2 = new MathOptr(dm.sub);
MathOptr d3 = new MathOptr(dm.mult);
MathOptr d4 = new MathOptr(dm.div);

d1(10, 20);
d2(20 , 10);
d3(10, 10);
d4(20, 5);

MathOptr d5 = d1 + d2 + d3 + d4;
d5(10,2);

Console.ReadKey();
}
} 3.7 SUMMARY: This chapter 3 gives the basic syntax of exception handling in C#. It discusses about exception, Assembly, Components of Assembly, Private and Shared Assembly, Garbage Collector, JIT compiler, Namespaces and few example programs. After learning the above topics, you can write many useful programs and built a strong foundation for larger programming projects. munotes.in

Page 83


83 Types, Objects, And
Namespaces 3.8 QUESTIONS: 1. Write a short note on Assembly. 2. What is the significance of Assemblies in .NET? 3. List and Explain the Components of assemblies. 4. How Garbage collector works? 5. Explain JIT compiler. 6. What is namespace? Explain System namespace. 3.9 REFERENCE: 1) The Complete Reference: C# 2) Visual C# 2012: How to program. 3) https://docs.microsoft.com/en-us/dotnet/csharp/  munotes.in

Page 84


84 Advanced Web Programming
84 4 WEB FORM FUNDAMENTALS 4.0 Objectives 4.1 Introduction 4.2 An Overview 4.2.1 Writing Code 4.2.2 Using the Code-Behind Class 4.2.3 Adding Event Handlers 4.3 Understanding the Anatomy of an ASP.NET Application 4.3.1 ASP.NET File Types 4.3.2 ASP.NET Web Folders 4.3.3 Debugging 4.4 Introducing Server Controls 4.4.1 HTML Server Controls 4.4.2 View State 4.4.3 Using the Page Class 4.4.4 Using Application Events 4.4.5 Configuring an ASP.NET Application. 4.5 Questions 4.6 References 4.0 OBJECTIVES After going through this unit, you will be able to:  To gain knowledge about what is web form and why it is used.  How to design a webform and its applications  How to write a code in C#.  Explain about the controls and its uses.  Various elements of Navigation. 4.1 INTRODUCTION Web Forms are web pages built on the ASP.NET Technology. It executes on the server and generates output to the browser. It is compatible to any browser to any language supported by .NET common language runtime. It is flexible and allows us to create and add custom controls. munotes.in

Page 85


85 AWP 4.2 AN OVERVIEW 4.2.1 Writing Code To start with writing a code i.e. dynamic and operational coding we need to switch to code-behind class. To switch up and down the code we use View code or View Designer buttons which appears just above the Solution Explorer window. Another approach is by double clicking either on .aspx page in the solution explorer or .aspx.cs page. Here we will be discussing C# code not the HTML code . 4.2.2 Using the Code-Behind class Code-Behind class refers to the code that is written in separate class file that has extension .aspx.cs or .aspx.vb depending on the language used. When we switch to code view we will see the page class for our webpage. For example when we create a webpage named SamplePage.aspx we will see a code behind class looks like this : Using System; Using.System.Collection.Generic; Using.System.Linq; Using.System.Web; Using.System.Web.UI; Using.System.Web.UI.WebControls; Public partial class SamplePage: System.Web.UI.Page { Protected void Page_Load(object sender , EventArgs e) { } } 4.2.3 Adding Event Handlers ASP.NET allows to implement event based model for our application. To create an event handler in properties window we do the following 1) Double-click to create a new event handler for that event. 2) Type the name of the handler to create. 3) In the drop-down list select the name of existing handler. For e.g:- The following diagram suggests that Select the Button and right click and click on properties. In the properties window click the yellow icon event munotes.in

Page 86


86 Advanced Web Programming
86 Or simple double click the button it will show code behind file where we can write the code if the user click button what action has to be performed.
public partialclass_EventHandlerDemo:System.Web.UI.Page { protected void Page_Load(object sender, Event Args e) { } protected void Button_Click(object sender, EventArgs e) { } } Where object sender represents the object raising the event. EventArgs represents the event arguments. 4.3 UNDERSTANDING THE ANATOMY OF AN ASP.NET APPLICATION ASP.NET pages are divided into multiple webpages. Every webpage shares a common resource and configuration. Each webpage is executed in separate application domain. If error occurs in application domain it does not affect other applications running on the same computer. Each web application is a combination of munotes.in

Page 87


87 AWP files, pages, handlers, modules and executable code that can be invoked from a virtual directory on the web server. 4.3.1 ASP.NET File Types 1) .aspx- This file is basically an extension of ASP.NET Web Pages. It is used for web form pages. 2) .ascx – This extension is basically used for web form user controls. The .ascx extension is often used for consistent parts of a website like headers, footers etc. 3) .asmx – This extension is used for files that implement ASP.NET Web Services. 4) .vb – This extension is used for VisualBasic.NET code modules. These files are code-behind files and are used to separate code from user interface. 5) .resx – These files are basically used for Windows Form Application for storing resources such as text strings for internationalization of applications. 6) Global.asax – These files are basically used to define Application-and-Session level variables and start up procedures. 4.3.2 ASP.NET Web Folders ASP.NET defines several special folders. These special folders can be added to a Web site from Visual Studio menu system. We can add it by right clicking the Website Application Project and selecting Add ASP.NET folder. The diagram shows the following :-
munotes.in

Page 88


88 Advanced Web Programming
88 ASP.Net folders are as follows:- 1) App_Browsers - ASP.net reserve this folder name for storing browser definition files. These files are used to determine the client browser capabilities and have .browser extension. 2) App_Code – App_code folder can contain source code for utility classes as well business objects (i.e .cs, .vb and .jsl files).The Classes that are present in App_Code folder are automatically compiled when your web application compiled. 3) App_Data - .App_Data folder is used by ASP.NET application for storing ASP.NET application local database. App_Data is used to store files that can be used as database files (.mdf and xml files). Developers can also use this folder for storing data for their ASP.NET Application. 4) App_GlobalResources - App_GlobalResources folder contains resources (.resx and .resources files) that are compiled into assemblies and have a global scope. These files are used to externalize text and images from our application code. This also helps us to support multiple languages and design-time changes without recompilation of your source code. These files are strongly typed and can be accessed programmatically. 5) App_LocalResources - App_LocalResources folder contains resources (.resx and .resources files). These files are available to a particular project, web page, master page or web user control. 6) App_Themes -These files contain subfolders that defines a specific theme or look and feel for your Web site. These consist of files (such as .skin, .css and image files) that defines the appearance of Web pages and controls. 7) App_WebReferences – It contains Web references files (.wsdl, .xsd, .disco, and .discomap files) that define references to Web services. 8) Bin - Bin folder contains compiled assemblies (.dll files) for code that we want to reference in our application. Assemblies in Bin folder are automatically reference in our application. 4.3.3 Debugging Debugging enables programmers to see how the Code works step-by-step, how the variables values change, how objects are created and destroyed, and so on. Debugging is the application’s method of inserting breakpoints. Such breakpoints are used to pause running a program from running. We start the debugging session using F5(Debug/Start Debugging). This command starts our app with the debugger attached. The Green arrow also starts the debugger
munotes.in

Page 89


89 AWP When running code in the debugger we often realize that we don’t need to see what happens to a particular function. We use some commands to skip through code Keyboard
Command Menu
Command Description F10 Step Over If a current line contains a func tion
call, Step Over runs the code then
suspends execution at the first line of
code after the called function returns. Shift+F11 Step Out Step Out continues running code and
suspends execution wh en the curr ent
function retur ns. Run to a specific location or function These methods are useful when we know exactly what code we want to inspect and where we want to start debugging.  Set breakpoints in the code :- To set a simple breakpoint in our code, open the source file in the Visual Studio editor. Set the cursor at the line of code where we want to suspend execution and then right-click in the code window to see the context menu and choose Breakpoint/Insert Breakpoint(or Press F9)  Run to the cursor location:- To run to the cursor location, place the cursor on an executable line of code in a source window. On the editors context menu, choose Run to Cursor.  Manually break into the code :- To break into the line of code in an executing app, choose Debug, Break All (Keyboard:Ctrl+Alt+Delete)  Run to a function on call stack :- In the Call Stack Window, select the function, right-click and choose Run to Cursor. When the site is executed for the first time, Visual Studio displays a prompt asking whether it should be enabled for debugging:
munotes.in

Page 90


90 Advanced Web Programming
90 4.4 INTRODUCTION TO SERVER CONTROLS The server controls are the heart of ASP.NET pages which represents dynamic elements that our user can interact with. Server controls are tags that are understood by the server. There are three kinds of server controls 1) HTML Server Controls – Traditional HTML tags. 2) Web Server Controls – New ASP.NET tags. 3) Validation server Controls – For input validation. Advantages of Server Controls  ASP .NET Server Controls can detect the target browser's capabilities and render themselves accordingly.  Newer set of controls that can be used in the same manner as any HTML control like Calender controls.  ASP .NET Server Controls have an object model different from the traditional HTML and even provide a set of properties and methods that can change the outlook and behavior of the controls.  ASP .NET Server Controls have higher level of abstraction. 4.4.1 HTML Server Controls :- The HTML elements are considered as text in ASP.NET file. They cannot be referred as server side code. These controls can be treated as server control by adding runat= “server” attribute. The id attribute in the element can be added as reference to the control. All the HTML server controls are written in the

tag. Some of the HTML Controls are as follows:-  HtmlAnchor – Controls an HTML element  HtmlButton – Controls a

Page 91


91 AWP  HtmlInputRadioButton -The HtmlInputRadioButton control is used to control an element.  HtmlSelect control - The HtmlSelect control is used to control