User:Gourab123/sandbox

Object Oriented Concept of Asp.net with C# Overview I wrote this book for better understanding the object oriented concept of asp.net with c#. I suggest you to follow this book if you likes. No matter what language you use but the best purpose of this book is for asp.net framework who use C# language.

Index Introduction                         				(Page 4-7) 1. An Overview ASP.NET with c#                         (Page 8-21)             1.A. Object					          (Page 8-9)                                            1.B. Class                                                               (Page 9-10)                                  1.C.Abstraction				                    (Page 10-12)    1.D.Encapsulation				          (Page 12-13)	  1.E.Inheritance                                               (Page 13-18 )                                       1.F.Polymorphism					(Page 18-21) 2. Data types and Variable      			(Page 22-28)			2.A.Data types                                                     (Page 22-23)                                                  	2.B.Character Escape Sequences			(Page 23-24)			2.C.The Array Type					(Page 24-28) 3. Control Statement-Selection                              (Page 29-32)  	3.A.If-else Example				        (Page 29-30)			3.B.Example of Switch statement	        (Page 30-31)			3.C.C# Branching Statements                         (Page 32) 4 .Control Statements – Loops    		        (Page 33-35)			4 A. while loop Example	                            (Page 33)				4.B. do loop Example				        (Page 33-34)			4.C.Example of for loop			        (Page 34)				4.D.Example of foreach loop                          (Page 34-35)                                             5.Namespace 				                            (Page 36-38)			5.A.Example of namespace                            (Page 36-37)			5.B.Namespace example using Directive     (Page 37-38) 6.Introduction to Classes				       (Page 39-43)		6.A.Constructor					        (Page 39-43)				6.A.i).Default Constructor		        (Page 39)					6.A.ii)Parameterized Constructor        (Page 39)					6.A.iii).Static Constructor	                  (Page 39)					6.A.iv).Copy Constructor                       (Page 40) 7.Properties		                                               (Page 44-49)			7.A.Example of Properties			        (Page 44-45)			7.B.Static Properties			                  (Page 45-46) 			7.C.Properties & Inheritance	                  (Page 46)				7.D.Properties & Polymorphism		        (Page 47-48)			7.E.Abstract Properties                                   (Page 48-49) 8. Interface						Page (50-51)				8.A.Defination of Interface			Page (50)					8.B.Example of Interface			Page (50-51) 9. Abstract Class					Page (52-55)			9.A.Example of Abstract class		Page (53-55)				9.B.Interface vs. Abstract class		Page (55) 10. Delegates and Events				Page(56-66)				10.A.Example of Delegate			Page(57-61)				10.B.Events					Page(61-62)				10.C.Example of Events			Page(62-66) 11. Exception Handling				Page(67-69)				11.A Example Of Exception Handling	Page(68-69) 12. Enums							Page(70-71)			12.A.Example Of Enums			Page(70-71) 13. Operator Overloading				Page(72-75)				13.A.Example of Binary Operator	Page(72-73)				13.B.Example of Unary Operator		Page(74-75) 14. Generic Collections				Page(76-82)				14.A.Example of Generic Collections	Page(80-82) 15. C# Type						Page(83-88)				15.A.Type Safety				Page(83-84)				15.B.Understanding Reference Types	Page(84)				15.C.Example of Reference Types	Page(84-86)				15.D.Understanding Value Types	Page(86)					15.E.Example of Value Types		Page(86-88) 16. A. Reference Type and Value Type Differences Page(89) History Arround 1995,java was gaining popularity because of its platform-independent approach and sun Microsystems’ open source policy. Later in 2002 Sun Microsystems released the enterprise Edition(J2EE) which is a Java platform to develop and execute distributed java application based on the N-tier architecture .The advent of J2EE led to decline of Microsoft ‘s share market. Consequently Microsoft Started a project called Next Generation Windows Service (NGWS) to regain the market share.It tooks more than three years to develop the product, which is khown as .NET. Microsoft released the first version of .NET with the name .NET framework 1.0 on February 13,2002 along with the Visual Studio.NET 2002 IDE.The second revised version of .NET took nearly an year to release and was known as .NET Framework 1.1.Microsoft Visual Studio .NET,better known as Visual Studio .NET 2003,was also part of the second release.The next version,.NET framework 2.0,was released with Visual Studio 2005 on november 07,2005. .NET framework 3.0,formerly called WinFX ,was released on November 06,2006. .NET framework 3.5 released with visual studio .NET 2008 on Nevember 19,2007.The latest version the .NET framework 4.0 was announced by microsoft on september 29,2008 and on April 12,2010,the final version of .NET framework was released.

Introduction

.NET Framework: The .NET Framework (pronounced dot net) is a software framework that runs primarily on Microsoft Windows. It includes a large library and provides language interoperability (each language can use code written in other languages) across several programming languages. Programs written for the .NET Framework execute in a software environment (as contrasted to hardware environment), known as the Common Language Runtime (CLR), an application virtual machine that provides important services such as security,memory management, and exception handling. The class library and the CLR together constitute the .NET Framework. The .NET Framework's Base Class Library provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. Programmers produce software by combining their own source code with the .NET Framework and other libraries. The .NET Framework is intended to be used by most new applications created for the Windows platform. Microsoft also produces a popular integrated development environment largely for .NET software called Visual Studio. Microsoft started the development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released. Version 3.0 of the .NET Framework is included with Windows Server 2008 and Windows Vista. Version 3.5 is included with Windows 7, and can also be installed on Windows XP and the Windows Server 2003 family of operating systems.[3] On 12 April 2010, .NET Framework 4 was released alongside Visual Studio 2010.

Version	Version Number	Release Date	Visual Studio	Default in Windows 1.0 1.0.3705.0	2002-02-13	Visual Studio .NET Windows XP Tablet and Media Center Editions[4]

1.1 1.1.4322.573	2003-04-24	Visual Studio .NET 2003	Windows Server 2003 2.0 2.0.50727.42	2005-11-07	Visual Studio 2005	Windows Server 2003 R2 3.0 3.0.4506.30	2006-11-06		Windows Vista, Windows Server 2008 3.5 3.5.21022.8	2007-11-19	Visual Studio 2008	Windows 7, Windows Server 2008 R2 4.0 4.0.30319.1	2010-04-12	Visual Studio 2010	Windows 7(Recommended) 4.5 4.5.40805	2012-02-29 (consumer preview)	Visual Studio '11'	Windows 8, Windows Server 8

Common Language Runtime(CLR): The common language runtime(CLR) is the virtual machine component of Microsoft's .NET framework and is responsible for managing the execution of .NET programs. In a process known as just-in-time (JIT) compilation, the CLR compiles the intermediate language code known as CIL into the machine instructions that in turn are executed by the computer's CPU. The CLR provides additional services including memory management, type safety and exception handling. All programs written for the .NET framework, regardless of programming language, are executed by the CLR. It provides exception handling, Garbage collection and thread management. Working Of CLR: When the .NET program is Compiled, the output of the compiler is not an executable code but a file that contains a special type of code called the Microsoft Intermediate Language(MSIL),which is a low-level set of instructions understood by the common language run time. The MSIL defines a set of portable instructions that are dependent of any specific CPU. It’s the job of the CLR to translate the Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that’s how the .NET framework achieves Portability. This MSIL is turned into executable code using a JIT(Just in time) compiler. The JIT compiler converts MSIL into native code on a demand basis as each part of the program is needed.

1)An Overview ASP.NET with c#

1.A Object: Object are runtime entities of an object oriented programming language, they may be a people, a bank account, a set of date, a place or any item that the program has to handle. They also may be any user defined data types such as vector, time, and list. We can say object are variable of type class. The definition of class is lesion letter in this season. Object:	Student

Data	Class Marks Name

Function Total Average Display

Example: using System;                     //Namespace Declaration using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication14 {   class Obj1 {       int cls; double marks; string name; Obj1(int c, double m, string n) //Parametarized Constructor {           cls = c;            marks = m;            name = n;        } void display //Instance Method/Function {           Console.WriteLine("class: {0} marks: {1} name: {2}",cls,marks,name); }

static void Main(string[] args) {           Obj1 a = new Obj1(9,55.5,"Arun"); //Instance of Obj1 //a is the object of class Obj1

a.display; //call Obj1 class method Console.ReadKey;

}   } }

Output: Class:9 marks:55.5 name:Arun. 1.B Class: Object contain code and data to manipulate data. The combination of this code and data can be made a user defined data type with the help of keyword class. Infact object are variable of type class. Once class has been declared we can use any no. of object belonging to that class. Each object are associated with data of type class with which they are declare. For example, mango are the object of class fruit. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication14 {   class Optclass {       string Name; public Optclass(string n)       { Name = n;       } public void display {         Console.WriteLine("Hello {0}", Name); }   }

class Exampleclass {

static void Main(string[] args) {           Optclass a = new Optclass("Amit");

a.display; Console.ReadKey;

}   } }

Output: Hello Amit. 1.C Abstraction: An essential element of object oriented programming is abstraction. Human manages complexity through abstraction. The concept of abstraction relates to the idea of hiding data that is not needed for presentation. The main idea behind abstraction is to give a clear separation between properties of data type and associated implementation details. This separation is achieved in order that the properties of abstract data type are visible to the user interface and the implementation details are hidden. There are two broad types of abstraction: •	functional abstraction •	data abstraction. Functional abstraction and data abstraction is that functional abstraction refers to a function that can be used without taking into account how the function is implemented. Data abstraction refers to the data that can be used without taking into account how the data are stored.

Reasons for the need of Abstraction Flexibility in approach: By hiding data or abstracting details that are not needed for presentation, the programmer achieves greater flexibility in approach. Enhanced Security: Abstraction gives access to data or details that are needed by users and hide the implementation details, giving enhanced security to application. Easier Replacement: With the concept of abstraction in object-oriented programming language, it is possible to replace code without recompilation. This makes the process easier and saves time for users. Access Labels Enforce Abstraction: •	Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members. •	Members defined with a private label are not accessible to code that uses the class. The private section hides the implementation from code that uses the type.

Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication14 {   class Abstraction {       Public

Abstraction(int i=0) {           total=i; }       public void add(int number) {           total+=number; }       public int gettotal {           return total; }       private int total;

}

class ExampleAbstraction {

static void Main(string[] args) {           Abstraction a=new Abstraction; a.add(10); a.add(20); a.add(30); Console.WriteLine("Total {0}", a.gettotal); Console.ReadKey;

}   } }

Output: 60

1.D Encapsulation: Encapsulation is a mechanism that binds together code and data it manipulates and keep both safe from outside interference an misuses. One way to think about encapsulation is as a protective wrapper. Access to the code inside the wrapper is tightly control through the wrapper. Access to the code inside the wrapper is tightly control through a well defined interface.

Type Member Access Modifiers: An access modifier allows you to specify the visibility of code outside a type or assembly.

Access Modifier 	Description (who can access) private 	Only members within the same type. (default for type members) protected 	Only derived types or members of the same type. internal 	Only code within the same assembly. Can also be code external to object as long as it is in the same assembly. (default for types) protected internal 	Either code from derived type or code in the same assembly. Combination of protected OR internal. public 	Any code. No inheritance, external type, or external assembly restrictions.

In C# the default access modifier is private. Encapsulation is achieved by declaring the variables as any of this access modifier. The examples of Access Modifier are discussed after the class of inheritance. 1.E Inheritance:  Inheritance is a process by which object of one class acquires the properties of object of another class. Inheritance is use the concept of reusability. i.e., we can add additional features to an existing class without modifying it. The new class has the combined features of both classes. The new class is called sub class or derived class and from which it is derived is called base class or super class.

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { int num1, num2; public A(int n1, int n2) {           num1 = n1; num2 = n2; }       public void display1 {           Console.Write("num1: {0} num2: {1}", num1, num2); }

}   class B : A    { int num3; public B(int n1, int n2, int n3) : base(n1, n2) {           num3 = n3; }       public void display2 {           display1; Console.Write("num3: {0}", num3); }   }

class Inheritance {       static void Main(string[] args) {           A superob = new A(3,5); Console.WriteLine("Contents of superclass"); superob.display1; B subob = new B(4,6,9); Console.WriteLine; Console.WriteLine("Contents of subclass"); subob.display2; Console.ReadKey; }

}

}

Output: Contents of super class                                                                                                        num1=3 num2=5                                                                                                               Contents of subclass										              num1=4 num2=6 num3=9 Now Comes the Example of Different types of Access Modifier: Example of public member access modifire: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { public int i,j; public void display {           Console.Write("num1: {0} num2: {1}", i, j); }

}   class PublicExample {       static void Main(string[] args) {           A a = new A; a.i = 5; a.j = 7; a.display; Console.ReadKey; }

}

}

Output: 											            num1:5 num2:7

Example of private member access modifire: Remember in C# the default access modifier is private. using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { private int i,j;

public void getdata(int a, int b)       { i = a;           j = b;        } public void display {           Console.Write("num1: {0} num2: {1}", i, j); }

}   class PrivateExample {       static void Main(string[] args) {           A a = new A; //a.i = 5; //not accessable due to access specifier is private //a.j = 7; //not accessable due to access specifier is private a.getdata(5,7); a.display; Console.ReadKey; }

}

}

Output:                                                                                                                    num1:5 num2:7

Example of protected member access modifire: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { protected int i,j;

protected A(int a,int b)       { i=a; j=b; }       protected void display {           Console.Write("num1: {0} num2: {1}", i, j); }

}   class B : A    { int k;       public B(int a, int b, int c)            : base(a, b)        { k = c;       }

public void display {           base.display; Console.WriteLine; Console.Write("num3:{0}", k); }   }    class ProtectedExample {       static void Main(string[] args) {           //A a = new A(7,9); //inaccasable due to protection level is protected //a.display;//inaccasable due to protection level is protected B b = new B(3,4,5);

//a.i = 5; //not accessable due to access specifier is private b.display; Console.ReadKey; }

}

}

Output: num1:3                                                                                                               num2:4                                                                                                                     num3:5 Two more access modifier here in c#(internal and protected internal) but this two access specifier not necessary. perhaps internal access specifier works like default access specifier used in java. Inside a class library the internal member are accessible but outside not whereas in java default member are accessible inside the package not outside the package. And the access modifier is protected internal which is the combination of protected and internal access modifier.

1.F Polymorphism: Polymorphism is a Greek word which means ability to make more than one form. An operator may exhibit different behavior depends upon the type of the data are used in the operation. For example for addition operation two operators produce a sum by addition. If the operators are two strings then the two string produce a third string by concatenation. The process of making operator that exhibit different behavior in different instance are called operator overloading. Polymorphism are two types : i)Compile-time Polymorphism/Method Overloading ii)Run-time Polymorphism/Method Overriding

i)Compile-time Polymorphism: Example of Compile time Polymorphism is Method Overloading. In C# it is possible to define two or more methods within the same class that share the same name as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded and the process is referred to method overloading. Method overloading is one of the way that c# implements run-time polymorphism.

Example of Method Overloading or Compile-time Polymorphism: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class OverloadDemo {

public void test {           Console.WriteLine("no parameter"); }       public void test(int a)        { Console.WriteLine("a={0}", a); }       public void test(int a,int b)        { Console.Write("a={0} ", a); Console.WriteLine("b={0}", b); }       public double test(double a)        { Console.WriteLine("double a={0}", a); return a * a;       } }

class Overload {       static void Main(string[] args) {           OverloadDemo ob = new OverloadDemo; double result; ob.test; ob.test(10); ob.test(10,20); result = ob.test(124.25); Console.WriteLine("Result of ob.test(124.25)= {0}", result);

Console.ReadKey; }

}

}

Output: no parameter                                                                                                a=10                                                                                                                a=10 b=20 Result of ob.test(124.25)= 15438.0625

ii)Run-time Polymorphism: Example of Run-time polymorphism is method overriding. In a class hierarchy, when a method in a sub class has the same name and type signature as a method in its super class, then the method in the subclass is said to override the method in super class. When an overridden method is called from within a sub class, it always refer to version of that method defined by super class will be hidden.

Example of Method Overriding or Run-time Polymorphism:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication16 {   class A    { int i, j;

public A(int a, int b)       { i = a;           j = b;        } public virtual void show {           Console.WriteLine(" i and j= {0} {1}", i, j); }   }    class B : A    { int k;       public B(int a, int b, int c)            : base(a, b)        { k = c;       } public override void show {           Console.WriteLine("k={0}", k); }   }

class Program {       static void Main(string[] args) {           A a;            B b;            a = new B(3,4,5); a.show; Console.ReadKey;

}   } }

Output: K=5

2.Datatypes And Variables

2.A.Data types: All types of c# are derived from a base class object. There are two types of data types. 1. Basic/build-in types(int,float,char) 2. User defined datatypes(class,struct,interface)

Integral Types: They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. Type 	Size (in bits) 	Range sbyte 	8 	-128 to 127 byte 	8 	0 to 255 short 	16 	-32768 to 32767 ushort 	16 	0 to 65535 int 	32 	-2147483648 to 2147483647 uint 	32 	0 to 4294967295 long 	64 	-9223372036854775808 to 9223372036854775807 ulong 	64 	0 to 18446744073709551615 char 	16 	0 to 65535 Floating Point and Decimal Types: A C# floating point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values. Type 	Size (in bits) 	precision 	Range float 	32 	7 digits 	1.5 x 10-45 to 3.4 x 1038 double 	64 	15-16 digits 	5.0 x 10-324 to 1.7 x 10308 decimal 	128 	28-29 decimal places 	1.0 x 10-28 to 7.9 x 1028 The string Type: A string is a sequence of text characters. The Boolean Type: Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, Boolean conditions can be satisfied where 0 means false and anything else means true. Memory allocation of the data type divides them into two types: 1. Value types(Which stores values):                                                            i)All basic or build-in types except strings                                                  ii)structs                                                                                                               iii)Enumeration(Enum types)							                             2.Reference types(which store references to the actual data)	:             i)class                                                                                                                ii)interface                                                                                                       iii)delegates                                                                                              iv)string                                                                                                         v)object 2.B.Character Escape Sequences: Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. Escape Sequence 	Meaning \' 	Single Quote \" 	Double Quote \\ 	Backslash \0 	Null, not the same as the C# null value \a 	Bell \b 	Backspace \f 	form Feed \n 	Newline \r 	Carriage Return \t 	Horizontal Tab \v 	Vertical Tab C# Operators: Category (by precedence) 	Operator(s) 	Associativity Primary 	x.y f(x)  a[x]  x++  x--  new  typeof  default  checked  unchecked delegate 	left Unary 	+  -  !  ~  ++x  --x  (T)x 	right Multiplicative 	*  /  % 	left Additive 	+  - 	left Shift 	<<  >> 	left Relational 	<  >  <=  >=  is as 	left Equality 	==  != 	right Logical AND 	& 	left Logical XOR 	^ 	left Logical OR 	| 	left Conditional AND 	&& 	left Conditional OR 	|| 	left Null Coalescing 	?? 	left Ternary 	?: 	right Assignment 	=  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=  => 	right Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left. 2.C.The Array Type: Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size. C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages there are, however, a few differences that you should be aware of. When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.

int[] table; // not int table[];

Declaring Arrays: C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The following examples show how to declare different kinds of arrays: Single-dimensional arrays: int[] numbers;                                Multidimensional arrays:    string[,] names;                                                                                                                                                                                    Array-of-arrays (jagged):     byte[][] scores;                          	         Three-dimensional arrays:   int[,,] buttons=new int[4,5,3]; Example of Single-dimentional array: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 {   class Array {       static void Main(string[] args) {           int [] month_days; month_days=new int[12]; month_days[0]=31; month_days[1]=29; month_days[2]=31; month_days[3]=30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; Console.WriteLine("April has {0} days",month_days[3]); Console.ReadKey;

}   } } Output: April has 30 days Or using System;                                                                                                                    using System.Collections.Generic;                                                                                           using System.Linq;                                                                                                                   using System.Text;                                                                                                                 namespace ConsoleApplication17 {   class AutoArray {       static void Main(string[] args) {           int [] month_days={31,29,31,30,31,30,31,31,30,31,30,31}; Console.WriteLine("April has {0} days",month_days[3]); Console.ReadKey; }   } } Output: April has 30 days Example of Twodimentional array: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 {   class TwoDArray {       static void Main(string[] args) {           int[,] twoD = new int[4, 5]; int i, j, k = 0; for (i = 0; i < 4; i++) {               for (j = 0; j < 5; j++) {

twoD[i, j] = k;                   k++; }           }            for (i = 0; i < 4; i++) {               for (j = 0; j < 5; j++) {                   Console.Write("{0} ",twoD[i, j]); }               Console.WriteLine; }

Console.ReadKey; }   } } Output:                                                                                                                  0 1 2 3 4                                                                                                                5 6 7 8 9                                                                                                              10 11 12 13 14                                                                                                    15 16 17 18 19 Example of jagged Array(Array of Arrays): using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication4 {   class Program {       static void Main(string[] args) {           int i, j, k;            int[][] jaggedAr = new int[4][]; jaggedAr[0] = new int[1]; jaggedAr[1] = new int[2]; jaggedAr[2] = new int[3]; jaggedAr[3] = new int[4]; k = 0; for (i = 0; i < 4; i++){ for (j = 0; j < i + 1; j++) {                   jaggedAr[i][j] = k;                    k++; }                                  }            for (i = 0; i < 4; i++){ for (j = 0; j < i + 1; j++) {                   Console.Write(jaggedAr[i][j] + " ");

}               Console.WriteLine; }           Console.ReadKey; }

} } Output: 0 1 2 3 4 5 6 7 8 9

One of the differences between jagged arrays, int[][] jaggedAr, and multi-dimension arrays, int TwoD[,], is that a multi-dimension array will allocate memory for every element of each dimension, whereas a jagged array will only allocate memory for the size of each array in each dimension that you define. Most of the time, you'll be using multi-dimension arrays, if you need multiple dimensions, and will only use jagged arrays in very special circumstances when you are able to save significant memory by explicitly specifying the sizes of the arrays in each dimension.

3.Control Statement-Selection

C# supports two selection statements: if and switch.

Syntax of if statement: If(condition) statement1; Else statement2;

Nested if example: If(i==10) { If(j<20) a=b; If(k>100) c=d; Else a=c; } Else a=d;

If-else-if Ladder syntax: If(condition) Statement; Else if(condition) Statement; Else if(condition) Statement; Else Statement

3.A.If-else Example:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication17

{   class IfElse {       static void Main(string[] args) {           int a,b,c; string opt; string i, j;           Console.WriteLine("Enter a"); i= Console.ReadLine; a = Int32.Parse(i); Console.WriteLine("Enter b"); j = Console.ReadLine; b = Int32.Parse(j);

Console.WriteLine("Enter the operator"); opt = Console.ReadLine;

if (opt == "+") c = a + b;           else if (opt == "-") c = a - b;           else if (opt == "*") c = a * b;           else c = a / b;

Console.WriteLine("Result={0}", c); Console.ReadKey; }   } }

Output:Enter a             5 Enter b             6 Enter the operator +             Result=11

3.B.Example of Switch statement:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 { class Switch {

static void Main(string[] args) {

int month = 4; string season; switch (month) {               case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; default: season = "Bogus month"; break; }           Console.WriteLine("April is in the {0}", season);

Console.ReadKey; }   } }

Output: April is in the Spring

3.C.C# Branching Statements: Branching statement 	Description break 	Leaves the switch block continue 	Leaves the switch block, skips remaining logic in enclosing loop, and goes back to loop condition to determine if loop should be executed again from the beginning. goto 	Leaves the switch block and jumps directly to a label of the form " :" return 	Leaves the current method. throw 	Throws an exception.

4.Control Statements – Loops

4.A.while loop Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 { class WhileLoop {   public static void Main {       int number = 0;

while (number < 10) {           Console.Write("{0} ", number); number++; }       Console.WriteLine; Console.ReadKey; } } }

Output:                                                                                                                 0 1 2 3 4 5 6 7 8 9 4.B.do loop Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 { class DoLoop {   public static void Main {       int number = 10;

do       { Console.Write("{0} ", number); number--;

}while (number > 0); Console.WriteLine; Console.ReadKey; } } }

Output:                                                                                                              10 9 8 7 6 5 4 3 2 1 4.C.Example of for loop: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 {

class ForLoop {       public static void Main {           for (int i = 0; i < 20; i++) {               if (i == 10) break;

if (i % 2 == 0) continue;

Console.Write("{0} ", i); }           Console.WriteLine; Console.ReadKey; } } }

Output:                                                                                                                 1 3 5 7 9 The foreach Loop: A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace.

4.D.Example of foreach loop:

using System; using System.Collections.Generic;

using System.Linq; using System.Text;

namespace ConsoleApplication17 {

class ForEachLoop {       public static void Main {           string[] names = { "Rahul", "Amit", "Sumit", "Kunal" };

foreach (string person in names) {               Console.WriteLine("{0} ", person); } Console.ReadKey; } } }

Output:                                                                                                              Rahul                                                                                                                         Amit                                                                                                                          Sumit                                                                                                                           Kunal

5.Namespace The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types. System.Console.WriteLine(“Hello World!”);

System is a namespace and Console is a class in that namespace. The using keyword can be used so that the complete name is not required, as in the following example: using system; Console.WriteLine(“Hello World!”);

5.A.Example of namespace:

//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text;

namespace Example1 {

class NamespaceExample {       public static void Main {           System.Console.WriteLine("This is the new c# namespace example"); System.Console.ReadKey; }   } }

Output:                                                                                                               This is the new c# namespace example Example of nested namespace:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace Example {

namespace Example1 {       class NamespaceExample {           public static void Main {               Console.WriteLine("This is the new c# nested namespace example 1"); Console.ReadKey; }       }    } }

Output: This is the new c# nested namespace example 1

Or using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace Example.Example1 {       class NamespaceExample {           public static void Main {               Console.WriteLine("This is the new c# nested namespace example 2"); Console.ReadKey; }       } }

Output: This is the new c# nested namespace example 2

5.B.Namespace example using Directive:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Example.Example1;

class UsingDirective {           public static void Main {               myexample.print; }       }        namespace Example.Example1 {           class myexample {

public static void print {                   Console.WriteLine("Emaple using Directive"); Console.ReadKey; }           }        }

Output:Example using Directive

6.Introduction to Classes Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces. Every class has a constructor.

6.A.Constructor:Constructor is a class member function that execute automatically whenever an object is created of the class. Constructor has the same name as class and it has no return type not even void. This is because the implicit return type of a class’ constructor is the class itself.

6.A.i).Default Constructor: Constructor with no parameter is called Default Constructor.

6.A.ii).Parameterized Constructor: Constructor that accepts arguments is known as parameterized constructor.

6.A.iii).Static Constructors: C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor). Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster. Static constructors are used to initializing class static data members. Point to be remembered while creating static constructor: 1. There can be only one static constructor in the class. 2. The static constructor should be without parameters. 3. It can only access the static members of the class. 4. There should be no access modifier in static constructor definition. 6.A.iv).Copy Constructor: If you create a new object and want to copy the values from an existing object, you use copy constructor. This constructor takes a single argument: a reference to the object to be copied. Exaple of Default Constructor:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   class Box {       double width; double height; double depth; public Box {           width = 10; height = 10; depth = 10; }       public double volume {           return width * height * depth; }   }    class DefaultConstructor {       static void Main(string[] args) {           Box mybox=new Box; double vol; vol=mybox.volume; Console.WriteLine("Volume is {0}",vol); Console.ReadKey; }   }

}

Output:Volume is 1000

Example of Parameterized Construcutor:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   class Box {       double width; double height; double depth; public Box(double w,double h,double d)       { width = w;           height = h;            depth = d;        } public double volume {           return width * height * depth; }   }    class ParaConstructor {       static void Main(string[] args) {           Box mybox=new Box(10,20,15); double vol; vol=mybox.volume; Console.WriteLine("Volume is {0}",vol); Console.ReadKey; }   }

}

Output:Volume is 3000 Example of Static Constructor: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   public class test {       static string name; static int age; static test {           Console.WriteLine("Using static constructor"); name = "Depak Kumar"; age = 23; }       public static void display {           Console.WriteLine("Using static function"); Console.WriteLine(name); Console.WriteLine(age); }   }    class StaticConstructor {       static void Main(string[] args) {           test.display; Console.ReadLine; }   }

} Output:                                                                                                         Using static constructor                                                                              Using static function                                                                                    Depak kumar                     					                                                  23 Example of Copy Constuctor: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   public class test {       int x;        string y;        public test {           x = 5; y = "Hello"; }       public test(int a, string s)        { x = a;           y = s;        } public test(test obj) {           x = obj.x;            y = obj.y;        } public void show {           Console.WriteLine(x); Console.WriteLine(y); }   }    class CopyConstructor {       static void Main(string[] args) {           test obj1 = new test; test obj2 = new test(8,"world"); test obj3=new test(obj2); obj3.show; Console.ReadLine; }   }

} Output:                                                                                                                 8                                                                                                                                             world

7.Properties In C#, properties are nothing but natural extension of data fields. They are usually known as 'smart fields' in C# community. We know that data encapsulation and hiding are the two fundamental characteristics of any object oriented programming language. In C#, data encapsulation is possible through either classes or structures. By using various access modifiers like private, public, protected, internal etc it is possible to control the accessibility of the class members. Usually inside a class, we declare a data field as private and will provide a set of public SET and GET methods to access the data fields. This is a good programming practice, since the data fields are not directly accessible outside the class. We must use the set/get methods to access the data fields. Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. Another benefit of properties over fields is that you can change their internal implementation over time. 7.A.Example of Properties: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   class MyClass {       private int x;        public int X        { get {               return x;            } set {               x = value; }       }    }    class PropertiesExample {       static void Main(string[] args) {           MyClass mc = new MyClass; mc.X = 10; int xVal = mc.X;           Console.WriteLine(xVal); Console.ReadLine; }   }

} Output:10 7.B.Static Properties: C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also. using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {

class MyClass {       private static int x;        public static int X        { get {               return x;            } set {               x = value; }       }    }    class MyClient {       public static void Main {           MyClass.X = 10; int xVal = MyClass.X;           Console.WriteLine(xVal); Console.ReadLine; }   } } Output:10 7.C.Properties & Inheritance: The properties of a Base class can be inherited to a Derived class. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {

using System; class Base {       private int x;        public int X        { get {               Console.Write("Base GET "); return x;           } set {               x = value;

}       }    }    class Derived : Base {   }    class MyClient {       public static void Main {           Derived d1 = new Derived; d1.X = 10; Console.WriteLine(d1.X); Console.ReadLine; }   } }

Output: Base GET 10

7.D.Properties & Polymorphism: A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication18 {   class Base {  private int x;        public virtual int X        { get {               Console.Write("Base GET"); return x;           } set {               x=value ; Console.Write("Base SET"); }       }    }    class Derived : Base {  private int x;        public override int X        { get {               Console.Write("Derived GET "); return x;           } set {               x = value; Console.Write("Derived SET "); }       }    }    class Mypropertiespoly {       public static void Main {           Base b1 = new Derived; b1.X = 10; Console.WriteLine(b1.X); Console.ReadLine; }   } } Output:Derived SET Derived GET 10 7.E.Abstract Properties:

A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors. If the abstract class contains only set accessor, we can implement only set in the derived class. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   abstract class Abstract {  private int x;        public abstract int X        { get; set; }   }    class Concrete : Abstract {  private int x;        public override int X        { get {               Console.Write("GET "); return x;           } set {               Console.Write("SET "); x = value;

}       }    }    class AbstractProperties {       public static void Main {           Concrete c1 = new Concrete; c1.X = 10; Console.WriteLine(c1.X); Console.ReadLine; }   }

} Output:SET GET 10

8.Interfaces

8.A.Defination of Interface: An interface is not a class. It is an entity that is defined by the word interface. An interface has no implementation, it has only the signature or in the other words, just the definition of the methods without any body. Since c# does not support multiple inheritance but the interface has the ability to implement multiple inheritance. 8.B.Example of Interface: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication19 {   public interface one {       void method1; }   public interface two {       void method2; }   public class example : one, two {       void one.method1 {           Console.WriteLine("First Interface"); }       void two.method2 {           Console.WriteLine("Second Interface"); }   }

class Interface {       static void Main(string[] args) {           example e = new example; one o;           o = (one)e; o.method1; two t;           t = (two)e; t.method2; Console.ReadLine;

}   } }

Output:                                                   			                                                   First Interface                    							                         Second Interface

9.Abstract Class An abstract class is a special kind of class that cannot be instantiated. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Abstract classes have the following features: •	An abstract class cannot be instantiated. •	An abstract class may contain abstract methods and accessors. •	It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. •	A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Abstract methods have the following features: •	An abstract method is implicitly a virtual method. •	Abstract method declarations are only permitted in abstract classes. •	Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example: public abstract void MyMethod;

•	The implementation is provided by an overriding method, which is a member of a non-abstract class. •	It is an error to use the static or virtual modifiers in an abstract method declaration. Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax. •	It is an error to use the abstract modifier on a static property. •	An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier. An abstract class must provide implementation for all interface members. An abstract class that implements an interface might map the interface methods onto abstract methods. For example: interface I { void M; } abstract class C: I { public abstract void M; } 9.A.Example of Abstractclass: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   abstract class vechicle {       public abstract void speed; public abstract void maintainance; public abstract void value; }   class Fourwheeler:vechicle {       public override void speed {           Console.WriteLine("In Speed of Fourwheeler"); }       public override void maintainance {           Console.WriteLine("In Maintaunance of Fourwheeler"); }       public override void value {           Console.WriteLine("In Value of Fourwheeler"); }   }    class Twowheeler:vechicle {       public override void speed {           Console.WriteLine("In Speed of Twowheeler"); }       public override void maintainance {           Console.WriteLine("In Maintaunance of Twowheeler"); }       public override void value {           Console.WriteLine("In Value of Twowheeler"); }   }    class AbstractExample {

static void Main(string [] args) {           vechicle maruti, bajaj; maruti = new Fourwheeler; bajaj = new Twowheeler; maruti.speed; maruti.maintainance; maruti.value; bajaj.speed; bajaj.maintainance; bajaj.value; Console.ReadKey; }   } }

Output:                                                                                                  In Speed of Fourwheeler In Maintaunance of Fourwheeler In Value of Fourwheeler                                                                                                  In Speed of Twowheeler In Maintaunance of Twowheeler In Value of Twowheeler

9.B.Interface vs Abstract class: i) In Interface a class may inherit several interfaces. And In Abstract class a class may inherit only one abstract class. ii) An Interface cannot provide any code, it provides just the signature. Whereas an abstract class can provide complete default code and/or just the details that have to overridden. iii) An Interface cannot have access modifier for the subs, functions, properties, etc everything is assumed as public. Whereas an abstract class can contain access modifiers for the subs, functions, properties which can private, public or protected. iv) In Interface it requires more time to find the actual method in the corresponding class whereas An Abstract works probably fast.

10.Delegates and Events

Definition 1: A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Definition 2: A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer. However, developers who have used other languages are probably wondering, "Why do I need a reference to a method?". The answer boils down to giving you maximum flexibility to implement any functionality you want at runtime. Definition 3: A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example: public delegate int PerformCalculation(int x, int y); Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method. This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way. Delegates have the following properties: •	Delegates are similar to C++ function pointers, but are type safe. •	Delegates allow methods to be passed as parameters. •	Delegates can be used to define callback methods. •	Delegates can be chained together; for example, multiple methods can be called on a single event. •	Methods don't need to match the delegate signature exactly. •	C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method. 10.A.Example of Delegate:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication20 {   public delegate int Comparer(object obj1, object obj2);

public class Name {       public string FirstName = null; public string LastName = null;

public Name(string first, string last) {           FirstName = first; LastName = last; }

// this is the delegate method handler public static int CompareFirstNames(object name1, object name2) {           string n1 = ((Name)name1).FirstName; string n2 = ((Name)name2).FirstName;

if (String.Compare(n1, n2) > 0) {               return 1; }           else if (String.Compare(n1, n2) < 0) {               return -1; }           else {               return 0; }       }

public override string ToString {           return FirstName + " " + LastName; }   }

class SimpleDelegate {       Name[] names = new Name[5];

public SimpleDelegate {           names[0] = new Name("Sumit", "Mandal"); names[1] = new Name("Saugata", "Bhandari"); names[2] = new Name("Sujit", "Mandal"); names[3] = new Name("Soumya", "Ghosh"); names[4] = new Name("Sayan", "Karmakar"); }

static void Main(string[] args) {           SimpleDelegate sd = new SimpleDelegate;

// this is the delegate instantiation Comparer cmp = new Comparer(Name.CompareFirstNames);

Console.WriteLine("\nBefore Sort: \n");

sd.PrintNames;

// observe the delegate argument sd.Sort(cmp);

Console.WriteLine("\nAfter Sort: \n");

sd.PrintNames; Console.ReadKey; }

// observe the delegate parameter public void Sort(Comparer compare) {           object temp;

for (int i = 0; i < names.Length; i++) {               for (int j = i; j < names.Length; j++) {                   // using delegate "compare" just like // a normal method if (compare(names[i], names[j]) > 0) {                       temp = names[i]; names[i] = names[j]; names[j] = (Name)temp; }               }            }        }

public void PrintNames {           Console.WriteLine("Names: \n");

foreach (Name name in names) {               Console.WriteLine(name.ToString); }       }    } }

Output:                               				                                                  Before Sort: Name: Sumit Mandal   						                                                  Saugata Bhandari       								                       Sujit Mandal                          							                      Soumya Ghosh                         				                               Sayan Karmakar After Sort: Name: Saugata Bhandari 						                                            Sayan Karmakar							                                            Soumya Ghosh    									    Sujit Mandal         						                                 Sumit Mandal Explanation Of the Above Program: The first thing this program is declarration of a delegate. Delegate declarations look somewhat like methods, except they have the delegate modifier, are terminated with a semi-colon, and have no implementation. Below, is the delegate declaration from: public delegate int Comparer(object obj1, object obj2); This delegate declaration defines the signature of a delegate handler method that this delegate can refer to. The delegate handler method, for the Comparer delegate, can have any name, but must have a first parameter of type object, a second parameter of type object, and return an int type. The following method shows a delegate handler method that conforms to the signature of the Comparer delegate. public static int CompareFirstNames(object name1, object name2) {       ...    } Note: The CompareFirstNames method calls String.Compare to compare the FirstName properties of the two Name instances. The String class has many convenience methods, such as Compare, for working with strings. Please don't allow the implementation of this method to interfere with learning how delegates work. What you should concentrate on is that CompareFirstNames is a handler method that a delegate can refer to, regardless of the code inside of that method. To use a delegate, you must create an instance of it. The instance is created, similar to a class instance, with a single parameter identifying the appropriate delegate handler method, as shown below. Comparer cmp = new Comparer(Name.CompareFirstNames); The delegate, cmp, is then used as a parameter to the Sort method, which uses it just like a normal method. Observe the way the delegate is passed to the Sort method as a parameter in the code below. sd.Sort(cmp); Using this technique, any delegate handler method may be passed to the Sort method at run-time. i.e. You could define a method handler named CompareLastNames, instantiate a new Comparer delegate instance with it, and pass the new delegate to the Sort method.

10.B.Events: A C# event is a class member that is activated whenever the event it was designed for occurs. I like to use the term "fires" when the event is activated. Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, registered methods will be invoked. Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.

10.C.Example of Events: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms;

namespace ConsoleApplication20 {   public delegate void Startdelegate;

class Eventdemo : Form {       // custom event public event Startdelegate StartEvent;

public Eventdemo {           Button clickMe = new Button;

clickMe.Parent = this; clickMe.Text = "Click Me"; clickMe.Location = new Point(               (ClientSize.Width - clickMe.Width) / 2,                (ClientSize.Height - clickMe.Height) / 2);

// an EventHandler delegate is assigned // to the button's Click event clickMe.Click += new EventHandler(OnClickMeClicked);

// our custom "Startdelegate" delegate is assigned // to our custom "StartEvent" event. StartEvent += new Startdelegate(OnStartEvent);

// fire our custom event StartEvent; }

// this method is called when the "clickMe" button is pressed public void OnClickMeClicked(object sender, EventArgs ea) {           MessageBox.Show("You Clicked My Button!"); }

// this method is called when the "StartEvent" Event is fired public void OnStartEvent {           MessageBox.Show("I Just Started!"); }

static void Main(string[] args) {           Application.Run(new Eventdemo); }   }

}

Output: Then Click ok Note: If you're using Visual Studio or another IDE, remember to add references to System.Drawing.dll and System.Windows.Forms.dll before compiling Listing 14.2 or just add the code to a Windows Forms project. You may have noticed that previous program is a Windows Forms program. Although I haven't covered Windows Forms in this tutorial, you should know enough about C# programming in general that you won't be lost. To help out, I'll give a brief explanation of some of the parts that you may not be familiar with. The Eventdemo class inherits Form, which essentially makes it a Windows Form. This automatically gives you all the functionality of a Windows Form, including Title Bar, Minimize/Maximize/Close buttons, System Menu, and Borders. The way a Windows Form's application is started is by calling the Run method of the static Application object with a reference to the form object as its parameter. This starts up all the underlying Windows plumbing, displays the GUI, and ensures that events are fired as appropriate. Let's look at the custom event first. Below is the event declaration, which is a member of the Eventdemo class. It is declared with the event keyword, a delegate type, and an event name. public event Startdelegate StartEvent;

Anyone interested in an event can register by hooking up a delegate for that event. On the next line, we have a delegate of type Startdelegate, which the event was declared to accept, hooked up to the StartEvent event. The += syntax registers a delegate with an event. To unregister with an event, use the -= with the same syntax. StartEvent += new Startdelegate(OnStartEvent);

Firing an event looks just like a method call, as shown below: StartEvent; This was how to implement events from scratch, declaring the event and delegate yourself. However, much of the event programming you'll do will be with pre-defined events and delegates. This leads us to the other event code you see in the previous program, where we hook up an EventHandler delegate to a Button Click event. clickMe.Click += new EventHandler(OnClickMeClicked); The Click event already belongs to the Button class and all we have to do is reference it when registering a delegate. Similarly, the EventHandler delegate already exists in the System namespace of the .NET Frameworks Class Library. All you really need to do is define your callback method (delegate handler method) that is invoked when someone presses the clickMe button. The OnClickMeClicked method, shown below, conforms to the signature of the EventHandler delegate, which you can look up in the .NET Framework Class Library reference. public void OnClickMeClicked(object sender, EventArgs ea) {       MessageBox.Show("You Clicked My Button!"); } Any time the clickMe button is pressed with a mouse, it will fire the Click event, which will invoke the OnClickMeClicked method. The Button class takes care of firing the Click event and there's nothing more you have to do. Because it is so easy to use pre-defined events and delegates, it would be a good idea to check if some exist already that will do what you need, before creating your own.

11.Exception Handling

Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. For example, validating user input, checking for null objects, and verifying the values returned from methods are what you expect, are all examples of good standard error handling that you should be doing all the time. An exception is an object that describes an exceptional condition (that is error) that has occurred in a piece of code. When a exception condition arises, an object representing that exception is created and thrown in the method that cause the error. That method may choose to handle the exception itself, or pass it on Either way, at some point, the exception is caught and processed. Exceptions can be generated by the run-time system or they can be manually generated by your code. C# Exception handling is manage by via four keywords:-try,catch,throw,finally. Program statements that you want to monitor for exception are contained within a try block. If an exception occurs within the try block, it is thrown, your code catch this exception (using catch) and handle it in some rational manner. System generated exception is automatically thrown by the java run-time system. To manually throw an exception, use the keyword throw. The System.Exception class provides several methods and properties for obtaining information on what went wrong. For example, the Message property provides summary information about what the error was, the Stacktrace property provides information from the stack for where the problem occurred, and the ToString method is overridden to reveal a verbose description of the entire exception. Identifying the exceptions you'll need to handle depends on the routine you're writing. For example, if the routine opened a file with the System.IO.File.OpenRead method, it could throw any of the following exceptions: •	SecurityException •	ArgumentException •	ArgumentNullException •	PathTooLongException •	DirectoryNotFoundException •	UnauthorizedAccessException •	FileNotFoundException •	NotSupportedException 11.A.Example Of Exception Handling: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class TryCatchDemo {       static void Main(string [] args) {           try {               int d = 0; int a = 42 / d;               Console.WriteLine("This will not be printed"); }           catch (ArithmeticException e)            { Console.WriteLine("Division by zero"); Console.WriteLine("After catch statement"); }             Console.ReadKey; }   } }

Output: Division by zero			                                                                  After catch statement

12.Enums Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast. Enums lend themselves to more maintainable code because they are symbolic, allowing you to work with integral values, but using a meaningful name to do so. For example, what type of code would you rather work with - a set of values named North, South, East, and West or the set of integers 0, 1, 2, and 3 that mapped to the same values, respectively? Enums make working with strongly typed constants via symbolic names easy. Enums are value types, which means they contain their own value, can't inherit or be inherited from, and assignment copies the value of one enum to another. You will see in this lesson and elsewhere that enums are used and referred to with both lower case, enum, and upper case, Enum. The relationship between the two is that the C# type, enum, inherits the Base Class Library (BCL) type, Enum. Use the C# type, enum, to define new enums and use the BCL type, Enum, to implement static enum methods. 12.A.Example Of Enums: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication20 {   public enum Volume {       Low, Medium, High }

// demonstrates how to use the enum

class EnumSwitch {       static void Main {           // create and initialize // instance of enum type Volume myVolume = Volume.Medium;

// make decision based // on enum value switch (myVolume) {               case Volume.Low: Console.WriteLine("The volume has been turned Down."); break; case Volume.Medium: Console.WriteLine("The volume is in the middle."); break; case Volume.High: Console.WriteLine("The volume has been turned up."); break; }           Console.ReadLine; }   } }

Output: The volume is in the middle.

13.Operator Overloading An operator may exhibit different behavior depends upon the type of the data are used in the operation. For example for addition operation two operators produce a sum by addition. If the operators are two strings then the two string produce a third string by concatenation. The process of making operator that exhibit different behavior in different instance are called operator overloading. The following set of operators is commonly overloaded for user-defined classes: •	= (assignment operator) •	+ - * (binary arithmetic operators) •	+= -= *= (compound assignment operators) •	== != (comparison operators) 13.A.Example Of Binary Operator: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class BOperation {       int data; string s;       public void getdata {           Console.WriteLine("Enter the numbers"); s=Console.ReadLine; data = Int32.Parse(s); }

static public BOperation operator +(BOperation x, BOperation y)       { BOperation result=new BOperation; result.data = x.data + y.data; return result; }       static public BOperation operator -(BOperation x, BOperation y)        { BOperation result = new BOperation; result.data = x.data - y.data; return result; }       static public BOperation operator *(BOperation x, BOperation y)        { BOperation result = new BOperation; result.data = x.data * y.data; return result; }       static public BOperation operator /(BOperation x, BOperation y)        { BOperation result = new BOperation; result.data = x.data / y.data; return result; }       public void show {           Console.WriteLine("{0}", data); }   }    class example {       static void Main(string[] args) {           BOperation obj1 = new BOperation; BOperation obj2 = new BOperation; BOperation obj3 = new BOperation; obj1.getdata; obj2.getdata; obj3 = obj1 + obj2; Console.WriteLine("Result of Addition:"); obj3.show; obj3 = obj1 - obj2; Console.WriteLine("Result of Substraction:"); obj3.show; obj3 = obj1 * obj2; Console.WriteLine("Result of Multiplication:"); obj3.show; obj3 = obj1 / obj2; Console.WriteLine("Result of Division:"); obj3.show; Console.ReadLine;

}

} }

Output:											 Enter the numbers:				                                                                         8                                                                                                                                    Enter the numbers:				                                                                          4 Result of Addition:							                                      12   	                                                                                                                             Result of Subtraction:							                                       4                                                                                                                                 Result of Multiplication:							                                       32       						                                                       Result of Divition:							                                       2 13.B.Example of Unary Operator: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class UOperation {       int data; string s;       public void getdata {           Console.WriteLine("Enter the number"); s = Console.ReadLine; data = Int32.Parse(s); }       static public UOperation operator ++(UOperation x)        { UOperation result = new UOperation; result.data = x.data++; return result; }       static public UOperation operator --(UOperation x)        { UOperation result = new UOperation; result.data = x.data--; return result; }       public void show {           Console.WriteLine("{0}", data); }   }    class Unaryexample {       static void Main(string[] args) {           UOperation obj1 = new UOperation; UOperation obj2 = new UOperation; obj1.getdata; obj2 = obj1++; Console.WriteLine("Result of ++ operator:"); obj2.show; obj2 = obj1--; Console.WriteLine("Result of -- operator:"); obj2.show; Console.ReadLine;

}

} }

Output:	                                                                                                                    Enter  the number                                                                                                             20                                                                                                                             Result of ++ Operator                                                                                                 21  			                                                                                                          Result of -- Operator                                                                                                 19

14.Generic Collections

In .NET v1.0 there were collections, such as the ArrayList for working with groups of objects. An ArrayList is much like an array, except it could automatically grow and offered many convenience methods that arrays don't have. The problem with ArrayList and all the other .NET v1.0 collections is that  they operate on type object. Since all objects derive from the object type, you can assign anything to an ArrayList. The problem with this is that you incur performance overhead converting value type objects to and from the object type and a single ArrayList could accidentally hold different types, which would cause hard to find errors at runtime because you wrote code to work with one type. Generic collections fix these problems. A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object. With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems. Creating Generic List Collections The pattern for using a generic List collection is similar to arrays. You declare the List, populate its members, then access the members. Here's a code example of how to use a List: List myInts = new List ;

myInts.Add(1); myInts.Add(2); myInts.Add(3); for (int i = 0; i < myInts.Count; i++) {	       Console.WriteLine("MyInts: {0}", myInts[i]); } The first thing you should notice is the generic collection List, which is referred to as List of int. If you looked in the documentation for this class, you would find that it is defined as List, where T could be any type. For example, if you wanted the list to work on string or Customer objects, you could define them as List or List and they would hold only string or Customer objects. In the example above, myInts holds only type int. Using the Add method, you can add as many int objects to the collection as you want. This is different from arrays, which have a fixed size. The List class has many more methods you can use, such as Contains, Remove, and more. There are two parts of the for loop that you need to know about. First, the condition uses the Count property of myInts. This is another difference between collections and arrays in that an array uses a Length property for the same thing. Next, the way to read from a specific position in the List collection, myInts[i], is the exact same syntax you use with arrays. The next time you start to use a single-dimension array, consider using a List instead. That said, be sure to let your solution fit the problem and use the best tool for the job. i.e. it's common to work with byte[] in many places in the .NET Framework. Working with Dictionary Collections Another very useful generic collection is the Dictionary, which works with key/value pairs. There is a non-generic collection, called a Hashtable that does the same thing, except that it operates on type object. However, as explained earlier in this lesson, you want to avoid the non-generic collections and use thier generic counterparts instead. The scenario I'll use for this example is that you have a list of Customers that you need to work with. It would be natural to keep track of these Customers via their CustomerID. The Dictionary example will work with instances of the following Customer class: public class Customer {       public Customer(int id, string name) {           ID = id; Name = name; }

private int m_id;

public int ID       { get { return m_id; } set { m_id = value; } }

private string m_name;

public string Name {           get { return m_name; } set { m_name = value; } }   }

The Customer class above has a constructor to make it easier to initialize. It also exposes its state via public properties. It isn't very sophisticated at this point, but that's okay because its only purpose is to help you learn how to use a Dictionary collection. The following example populates a Dictionary collection with Customer objects and then shows you how to extract entries from the Dictionary: Dictionary customers = new Dictionary;

Customer cust1 = new Customer(1, "Cust 1"); Customer cust2 = new Customer(2, "Cust 2"); Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1); customers.Add(cust2.ID, cust2); customers.Add(cust3.ID, cust3);

foreach (KeyValuePair custKeyVal in customers) {       Console.WriteLine(            "Customer ID: {0}, Name: {1}",            custKeyVal.Key,            custKeyVal.Value.Name); } The customers variable is declared as a Dictionary. Considering that the formal declaration of Dictionary is Dictionary, the meaning of customers is that it is a Dictionary where the key is type int and the value is type Customer. Therefore, any time you add an entry to the Dictionary, you must provide the key because it is also the key that you will use to extract a specified Customer from the Dictionary.

I created three Customer objects, giving each an ID and a Name. I'll use the ID as the key and the entire Customer object as the value. You can see this in the calls to Add, where custX.ID is added as the key (first parameter) and the custX instance is added as the value (second parameter). Extracting information from a Dictionary is a little bit different. Iterating through the customers Dictionary with a foreach loop, the type returned is KeyValuePair, where TKey is type int and TValue is type Customer because those are the types that the customers Dictionary is defined with. Since custKeyVal is type KeyValuePair it has Key and Value properties for you to read from. In our example, custKeyVal.Key will hold the ID for the Customer instance and custKeyVal.Value will hold the whole Customer instance. The parameters in the Console.WriteLine statement demonstrate this by printing out the ID, obtained through the Key property, and the Name, obtained through the Name property of the Customer instance that is returned by the Value property. The Dictionary type is handy for those situations where you need to keep track of objects via some unique identifier. For your convenience, here's Listing 20-1, shows how both the List and Dictionary collections work. 14.A.Example of Generic Collections: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication21 {   public class Customer {       public Customer(int id, string name) {           ID = id; Name = name;

}

private int m_id;

public int ID       { get { return m_id; } set { m_id = value; } }

private string m_name;

public string Name {           get { return m_name; } set { m_name = value; } }   }

class GenericCollection {       static void Main(string[] args) {           List myInts = new List ;

myInts.Add(1); myInts.Add(2); myInts.Add(3);

for (int i = 0; i < myInts.Count; i++) {               Console.WriteLine("MyInts: {0}", myInts[i]); }

Dictionary customers = new Dictionary;

Customer cust1 = new Customer(1, "Cust 1"); Customer cust2 = new Customer(2, "Cust 2"); Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1); customers.Add(cust2.ID, cust2); customers.Add(cust3.ID, cust3);

foreach (KeyValuePair<int, Customer> custKeyVal in customers) {               Console.WriteLine(                    "Customer ID: {0}, Name: {1}",                    custKeyVal.Key,                    custKeyVal.Value.Name); }

Console.ReadKey; }   } }

Output:                 				                                                                MyInts: 1		                                                                                                   MyInts: 2                                                                                                                 MyInts: 3         	                                                                                                    Customer ID: 1, Name:  Cust 1                                                                        Customer ID: 2, Name:  Cust 2                                                                             Customer ID: 3, Name:  Cust 3

15.C# Type 15.A.Type Safety: In untyped languages, such as scripting languages, you can assign one variable to another and the compiler/interpreter will use an intelligent algorithm to figure out how the assignment should be done. If the assignment is between two variables of the same type, all is good. However, if the assignment is between different types, you could have serious problems. For example, if you assigned an int value to a float variable it would convert okay because the fractional part of the new float would just be zero. However, if you went the other way and assigned a float value to an int variable, that would most likely be a problem. You would lose all of the precision of the original float value. Consider the damage that could be caused if the float value represented a chemical ingredient, an engineering measurement, or a financial value. Finding such an error would be difficult and particularly expensive, especially if the error didn't show up until your application was in production (already being used by customers). Example of an implicit conversion, which doesn't require the cast operator, and an explicit conversion: using System;

class Program {   static void Main {       float lengthFloat = 7.35f;

// lose precision - explicit conversion int lengthInt = (int)lengthFloat;

// no problem - implicit conversion double lengthDouble = lengthInt;

Console.WriteLine("lengthInt = " + lengthInt); Console.WriteLine("lengthDouble = " + lengthDouble); Console.ReadKey; }

Output:                                                                                                           lengthInt = 7 lengthDouble = 7 Since a float, lengthFloat, has a fractional part but  an int, lengthInt, doesn't; the types aren't compatible. Because of type safety, C# won't allow you to assign lengthFloat directly to lengthInt, which would be dangerous. For your protection, you must use a cast operator, (int), to force the explicit conversion of lengthFloat to lengthInt. In the output, you can see that lengthInt is 7, showing that it lost the fractional part of the 7.35f value from lengthFloat. The assignment from lengthInt to lengthDouble is safe because a double is 64-bit and an int is 32-bit, meaning that you won't lose information. Therefore, the conversion is implicit, meaning that you can perform the assignment without the cast operator. 15.B.Understanding Reference Types: Reference type variables are named appropriately (reference) because the variable holds a reference to an object. In C and C++, you have something similar that is called a pointer, which points to an object. While you can modify a pointer, you can't modify the value of a reference - it simply points at the object in memory. An important fact you need to understand is  that when you are assigning one reference type variable to another, only the reference is copied, not  the object. The variable holds the reference and that is what is being copied. 15.C.Example of Reference Types: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class Employee {       private string m_name;

public string Name {           get { return m_name; } set { m_name = value; } }   }

class ReferenceType {       static void Main {           Employee joe = new Employee; joe.Name = "Joe";

Employee bob = new Employee; bob.Name = "Bob";

Console.WriteLine("Original Employee Values:"); Console.WriteLine("joe = " + joe.Name); Console.WriteLine("bob = " + bob.Name);

// assign joe reference to bob variable bob = joe;

Console.WriteLine; Console.WriteLine("Values After Reference Assignment:"); Console.WriteLine("joe = " + joe.Name); Console.WriteLine("bob = " + bob.Name);

joe.Name = "Bobbi Jo";

Console.WriteLine; Console.WriteLine("Values After Changing One Instance:"); Console.WriteLine("joe = " + joe.Name); Console.WriteLine("bob = " + bob.Name);

Console.ReadKey; }   } }

Output:                                                   Original Employee Values: joe = Joe bob = Bob

Values After Reference Assignment: joe = Joe bob = Joe Values After Changing One Instance: joe = Bobbi Jo bob = Bobbi Jo

I created two Employee instances, joe and bob. You can see in the output that the Name properties of both Employee instances each show their assigned values from when the objects were first created. After assigning joe to bob, the value of the Name properties of both instances are the same. This is what you might expect to see. What might surprise you is the values that occur after assigning a value to the Employee instance variable named joe. If you look at the code closely, you'll notice that it doesn't change bob - only Joe. However, the results from the output show that the Name property in bob is the same as the Name property in joe. This demonstrates that after assigning joe to bob, both variables held references to the joe object. Only the reference was copied - not the object. This is why you see the results of printing Name in both joe and bob are the same because the change was on the object that they both refer to. 15.D.Understanding Value Types: Value type variables, as their name (value) suggests, hold the object value. A value type variable holds its own copy of an object and when you perform assignment from one value type variable to another, both the left-hand-side and right-hand-side of the assignment hold two separate copies of that value. 15.E.Example of Value Types: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   struct Height {       private int m_inches;

public int Inches {           get { return m_inches; } set { m_inches = value; } }   }

class ValueType {       static void Main {           Height joe = new Height; joe.Inches = 71;

Height bob = new Height; bob.Inches = 59;

Console.WriteLine("Original Height Values:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches);

// assign joe value to bob variable bob = joe;

Console.WriteLine; Console.WriteLine("Values After Value Assignment:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches);

joe.Inches = 65;

Console.WriteLine; Console.WriteLine("Values After Changing One Instance:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches);

Console.ReadKey; }   } }

Output:                                                                Original Height Values: joe = 71 bob = 59

Values After Value Assignment: joe = 71 bob = 71

Values After Changing One Instance: joe = 65 bob = 71 In this example you can see that the Inches property of bob and joe are initially set to different values. After assigning joe to bob, a value copy

occurs, where both of the variables have the same value, but are two separate copies. To demonstrate value assignment results, notice what happens after setting joe to 65; The output shows that bob did not change, which demonstrates that value types hold distinct copies of their objects. The following types are value types: •	enum •	struct Note: All of the primitive types (int, char, double, etc.), except for string, are value types.

16.A.Reference Type and Value Type Differences: From the previous paragraphs, you might already see that there is a difference reference type and value type assignment. Reference types copy a reference to an object and value types copy the object. If you don't know this, then the effects can be surprising in your code when performing tasks such as making assignments and passing arguments to methods.

ASP.NET with c# by gourab
Object Oriented Concept of Asp.net with C# Overview I wrote this book for better understanding the object oriented concept of asp.net with c#. I suggest you to follow this book if you likes. No matter what language you use but the best purpose of this book is for asp.net framework who use C# language.

Index Introduction                         				(Page 4-7) 1. An Overview ASP.NET with c#                         (Page 8-21)             1.A. Object					          (Page 8-9)                                            1.B. Class                                                               (Page 9-10)                                  1.C.Abstraction				                    (Page 10-12)    1.D.Encapsulation				          (Page 12-13)	  1.E.Inheritance                                               (Page 13-18 )                                       1.F.Polymorphism					(Page 18-21) 2. Data types and Variable      			(Page 22-28)			2.A.Data types                                                     (Page 22-23)                                                  	2.B.Character Escape Sequences			(Page 23-24)			2.C.The Array Type					(Page 24-28) 3. Control Statement-Selection                              (Page 29-32)  	3.A.If-else Example				        (Page 29-30)			3.B.Example of Switch statement	        (Page 30-31)			3.C.C# Branching Statements                         (Page 32) 4 .Control Statements – Loops    		        (Page 33-35)			4 A. while loop Example	                            (Page 33)				4.B. do loop Example				        (Page 33-34)			4.C.Example of for loop			        (Page 34)				4.D.Example of foreach loop                          (Page 34-35)                                             5.Namespace 				                            (Page 36-38)			5.A.Example of namespace                            (Page 36-37)			5.B.Namespace example using Directive     (Page 37-38) 6.Introduction to Classes				       (Page 39-43)		6.A.Constructor					        (Page 39-43)				6.A.i).Default Constructor		        (Page 39)					6.A.ii)Parameterized Constructor        (Page 39)					6.A.iii).Static Constructor	                  (Page 39)					6.A.iv).Copy Constructor                       (Page 40) 7.Properties		                                               (Page 44-49)			7.A.Example of Properties			        (Page 44-45)			7.B.Static Properties			                  (Page 45-46) 			7.C.Properties & Inheritance	                  (Page 46)				7.D.Properties & Polymorphism		        (Page 47-48)			7.E.Abstract Properties                                   (Page 48-49) 8. Interface						Page (50-51)				8.A.Defination of Interface			Page (50)					8.B.Example of Interface			Page (50-51) 9. Abstract Class					Page (52-55)			9.A.Example of Abstract class		Page (53-55)				9.B.Interface vs. Abstract class		Page (55) 10. Delegates and Events				Page(56-66)				10.A.Example of Delegate			Page(57-61)				10.B.Events					Page(61-62)				10.C.Example of Events			Page(62-66) 11. Exception Handling				Page(67-69)				11.A Example Of Exception Handling	Page(68-69) 12. Enums							Page(70-71)			12.A.Example Of Enums			Page(70-71) 13. Operator Overloading				Page(72-75)				13.A.Example of Binary Operator	Page(72-73)				13.B.Example of Unary Operator		Page(74-75) 14. Generic Collections				Page(76-82)				14.A.Example of Generic Collections	Page(80-82) 15. C# Type						Page(83-88)				15.A.Type Safety				Page(83-84)				15.B.Understanding Reference Types	Page(84)				15.C.Example of Reference Types	Page(84-86)				15.D.Understanding Value Types	Page(86)					15.E.Example of Value Types		Page(86-88) 16. A. Reference Type and Value Type Differences Page(89) History Arround 1995,java was gaining popularity because of its platform-independent approach and sun Microsystems’ open source policy. Later in 2002 Sun Microsystems released the enterprise Edition(J2EE) which is a Java platform to develop and execute distributed java application based on the N-tier architecture .The advent of J2EE led to decline of Microsoft ‘s share market. Consequently Microsoft Started a project called Next Generation Windows Service (NGWS) to regain the market share.It tooks more than three years to develop the product, which is khown as .NET. Microsoft released the first version of .NET with the name .NET framework 1.0 on February 13,2002 along with the Visual Studio.NET 2002 IDE.The second revised version of .NET took nearly an year to release and was known as .NET Framework 1.1.Microsoft Visual Studio .NET,better known as Visual Studio .NET 2003,was also part of the second release.The next version,.NET framework 2.0,was released with Visual Studio 2005 on november 07,2005. .NET framework 3.0,formerly called WinFX ,was released on November 06,2006. .NET framework 3.5 released with visual studio .NET 2008 on Nevember 19,2007.The latest version the .NET framework 4.0 was announced by microsoft on september 29,2008 and on April 12,2010,the final version of .NET framework was released.

Introduction

.NET Framework: The .NET Framework (pronounced dot net) is a software framework that runs primarily on Microsoft Windows. It includes a large library and provides language interoperability (each language can use code written in other languages) across several programming languages. Programs written for the .NET Framework execute in a software environment (as contrasted to hardware environment), known as the Common Language Runtime (CLR), an application virtual machine that provides important services such as security,memory management, and exception handling. The class library and the CLR together constitute the .NET Framework. The .NET Framework's Base Class Library provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. Programmers produce software by combining their own source code with the .NET Framework and other libraries. The .NET Framework is intended to be used by most new applications created for the Windows platform. Microsoft also produces a popular integrated development environment largely for .NET software called Visual Studio. Microsoft started the development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released. Version 3.0 of the .NET Framework is included with Windows Server 2008 and Windows Vista. Version 3.5 is included with Windows 7, and can also be installed on Windows XP and the Windows Server 2003 family of operating systems.[3] On 12 April 2010, .NET Framework 4 was released alongside Visual Studio 2010.

Version	Version Number	Release Date	Visual Studio	Default in Windows 1.0 1.0.3705.0	2002-02-13	Visual Studio .NET Windows XP Tablet and Media Center Editions[4]

1.1 1.1.4322.573	2003-04-24	Visual Studio .NET 2003	Windows Server 2003 2.0 2.0.50727.42	2005-11-07	Visual Studio 2005	Windows Server 2003 R2 3.0 3.0.4506.30	2006-11-06		Windows Vista, Windows Server 2008 3.5 3.5.21022.8	2007-11-19	Visual Studio 2008	Windows 7, Windows Server 2008 R2 4.0 4.0.30319.1	2010-04-12	Visual Studio 2010	Windows 7(Recommended) 4.5 4.5.40805	2012-02-29 (consumer preview)	Visual Studio '11'	Windows 8, Windows Server 8

Common Language Runtime(CLR): The common language runtime(CLR) is the virtual machine component of Microsoft's .NET framework and is responsible for managing the execution of .NET programs. In a process known as just-in-time (JIT) compilation, the CLR compiles the intermediate language code known as CIL into the machine instructions that in turn are executed by the computer's CPU. The CLR provides additional services including memory management, type safety and exception handling. All programs written for the .NET framework, regardless of programming language, are executed by the CLR. It provides exception handling, Garbage collection and thread management. Working Of CLR: When the .NET program is Compiled, the output of the compiler is not an executable code but a file that contains a special type of code called the Microsoft Intermediate Language(MSIL),which is a low-level set of instructions understood by the common language run time. The MSIL defines a set of portable instructions that are dependent of any specific CPU. It’s the job of the CLR to translate the Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that’s how the .NET framework achieves Portability. This MSIL is turned into executable code using a JIT(Just in time) compiler. The JIT compiler converts MSIL into native code on a demand basis as each part of the program is needed.

1)An Overview ASP.NET with c#

1.A Object: Object are runtime entities of an object oriented programming language, they may be a people, a bank account, a set of date, a place or any item that the program has to handle. They also may be any user defined data types such as vector, time, and list. We can say object are variable of type class. The definition of class is lesion letter in this season. Object:	Student

Data	Class Marks Name

Function Total Average Display

Example: using System;                     //Namespace Declaration using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication14 {   class Obj1 {       int cls; double marks; string name; Obj1(int c, double m, string n) //Parametarized Constructor {           cls = c;            marks = m;            name = n;        } void display //Instance Method/Function {           Console.WriteLine("class: {0} marks: {1} name: {2}",cls,marks,name); }

static void Main(string[] args) {           Obj1 a = new Obj1(9,55.5,"Arun"); //Instance of Obj1 //a is the object of class Obj1

a.display; //call Obj1 class method Console.ReadKey;

}   } }

Output: Class:9 marks:55.5 name:Arun. 1.B Class: Object contain code and data to manipulate data. The combination of this code and data can be made a user defined data type with the help of keyword class. Infact object are variable of type class. Once class has been declared we can use any no. of object belonging to that class. Each object are associated with data of type class with which they are declare. For example, mango are the object of class fruit. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication14 {   class Optclass {       string Name; public Optclass(string n)       { Name = n;       } public void display {         Console.WriteLine("Hello {0}", Name); }   }

class Exampleclass {

static void Main(string[] args) {           Optclass a = new Optclass("Amit");

a.display; Console.ReadKey;

}   } }

Output: Hello Amit. 1.C Abstraction: An essential element of object oriented programming is abstraction. Human manages complexity through abstraction. The concept of abstraction relates to the idea of hiding data that is not needed for presentation. The main idea behind abstraction is to give a clear separation between properties of data type and associated implementation details. This separation is achieved in order that the properties of abstract data type are visible to the user interface and the implementation details are hidden. There are two broad types of abstraction: •	functional abstraction •	data abstraction. Functional abstraction and data abstraction is that functional abstraction refers to a function that can be used without taking into account how the function is implemented. Data abstraction refers to the data that can be used without taking into account how the data are stored.

Reasons for the need of Abstraction Flexibility in approach: By hiding data or abstracting details that are not needed for presentation, the programmer achieves greater flexibility in approach. Enhanced Security: Abstraction gives access to data or details that are needed by users and hide the implementation details, giving enhanced security to application. Easier Replacement: With the concept of abstraction in object-oriented programming language, it is possible to replace code without recompilation. This makes the process easier and saves time for users. Access Labels Enforce Abstraction: •	Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members. •	Members defined with a private label are not accessible to code that uses the class. The private section hides the implementation from code that uses the type.

Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication14 {   class Abstraction {       Public

Abstraction(int i=0) {           total=i; }       public void add(int number) {           total+=number; }       public int gettotal {           return total; }       private int total;

}

class ExampleAbstraction {

static void Main(string[] args) {           Abstraction a=new Abstraction; a.add(10); a.add(20); a.add(30); Console.WriteLine("Total {0}", a.gettotal); Console.ReadKey;

}   } }

Output: 60

1.D Encapsulation: Encapsulation is a mechanism that binds together code and data it manipulates and keep both safe from outside interference an misuses. One way to think about encapsulation is as a protective wrapper. Access to the code inside the wrapper is tightly control through the wrapper. Access to the code inside the wrapper is tightly control through a well defined interface.

Type Member Access Modifiers: An access modifier allows you to specify the visibility of code outside a type or assembly.

Access Modifier 	Description (who can access) private 	Only members within the same type. (default for type members) protected 	Only derived types or members of the same type. internal 	Only code within the same assembly. Can also be code external to object as long as it is in the same assembly. (default for types) protected internal 	Either code from derived type or code in the same assembly. Combination of protected OR internal. public 	Any code. No inheritance, external type, or external assembly restrictions.

In C# the default access modifier is private. Encapsulation is achieved by declaring the variables as any of this access modifier. The examples of Access Modifier are discussed after the class of inheritance. 1.E Inheritance:  Inheritance is a process by which object of one class acquires the properties of object of another class. Inheritance is use the concept of reusability. i.e., we can add additional features to an existing class without modifying it. The new class has the combined features of both classes. The new class is called sub class or derived class and from which it is derived is called base class or super class.

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { int num1, num2; public A(int n1, int n2) {           num1 = n1; num2 = n2; }       public void display1 {           Console.Write("num1: {0} num2: {1}", num1, num2); }

}   class B : A    { int num3; public B(int n1, int n2, int n3) : base(n1, n2) {           num3 = n3; }       public void display2 {           display1; Console.Write("num3: {0}", num3); }   }

class Inheritance {       static void Main(string[] args) {           A superob = new A(3,5); Console.WriteLine("Contents of superclass"); superob.display1; B subob = new B(4,6,9); Console.WriteLine; Console.WriteLine("Contents of subclass"); subob.display2; Console.ReadKey; }

}

}

Output: Contents of super class                                                                                                        num1=3 num2=5                                                                                                               Contents of subclass										              num1=4 num2=6 num3=9 Now Comes the Example of Different types of Access Modifier: Example of public member access modifire: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { public int i,j; public void display {           Console.Write("num1: {0} num2: {1}", i, j); }

}   class PublicExample {       static void Main(string[] args) {           A a = new A; a.i = 5; a.j = 7; a.display; Console.ReadKey; }

}

}

Output: 											            num1:5 num2:7

Example of private member access modifire: Remember in C# the default access modifier is private. using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { private int i,j;

public void getdata(int a, int b)       { i = a;           j = b;        } public void display {           Console.Write("num1: {0} num2: {1}", i, j); }

}   class PrivateExample {       static void Main(string[] args) {           A a = new A; //a.i = 5; //not accessable due to access specifier is private //a.j = 7; //not accessable due to access specifier is private a.getdata(5,7); a.display; Console.ReadKey; }

}

}

Output:                                                                                                                    num1:5 num2:7

Example of protected member access modifire: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class A    { protected int i,j;

protected A(int a,int b)       { i=a; j=b; }       protected void display {           Console.Write("num1: {0} num2: {1}", i, j); }

}   class B : A    { int k;       public B(int a, int b, int c)            : base(a, b)        { k = c;       }

public void display {           base.display; Console.WriteLine; Console.Write("num3:{0}", k); }   }    class ProtectedExample {       static void Main(string[] args) {           //A a = new A(7,9); //inaccasable due to protection level is protected //a.display;//inaccasable due to protection level is protected B b = new B(3,4,5);

//a.i = 5; //not accessable due to access specifier is private b.display; Console.ReadKey; }

}

}

Output: num1:3                                                                                                               num2:4                                                                                                                     num3:5 Two more access modifier here in c#(internal and protected internal) but this two access specifier not necessary. perhaps internal access specifier works like default access specifier used in java. Inside a class library the internal member are accessible but outside not whereas in java default member are accessible inside the package not outside the package. And the access modifier is protected internal which is the combination of protected and internal access modifier.

1.F Polymorphism: Polymorphism is a Greek word which means ability to make more than one form. An operator may exhibit different behavior depends upon the type of the data are used in the operation. For example for addition operation two operators produce a sum by addition. If the operators are two strings then the two string produce a third string by concatenation. The process of making operator that exhibit different behavior in different instance are called operator overloading. Polymorphism are two types : i)Compile-time Polymorphism/Method Overloading ii)Run-time Polymorphism/Method Overriding

i)Compile-time Polymorphism: Example of Compile time Polymorphism is Method Overloading. In C# it is possible to define two or more methods within the same class that share the same name as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded and the process is referred to method overloading. Method overloading is one of the way that c# implements run-time polymorphism.

Example of Method Overloading or Compile-time Polymorphism: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication15 {   class OverloadDemo {

public void test {           Console.WriteLine("no parameter"); }       public void test(int a)        { Console.WriteLine("a={0}", a); }       public void test(int a,int b)        { Console.Write("a={0} ", a); Console.WriteLine("b={0}", b); }       public double test(double a)        { Console.WriteLine("double a={0}", a); return a * a;       } }

class Overload {       static void Main(string[] args) {           OverloadDemo ob = new OverloadDemo; double result; ob.test; ob.test(10); ob.test(10,20); result = ob.test(124.25); Console.WriteLine("Result of ob.test(124.25)= {0}", result);

Console.ReadKey; }

}

}

Output: no parameter                                                                                                a=10                                                                                                                a=10 b=20 Result of ob.test(124.25)= 15438.0625

ii)Run-time Polymorphism: Example of Run-time polymorphism is method overriding. In a class hierarchy, when a method in a sub class has the same name and type signature as a method in its super class, then the method in the subclass is said to override the method in super class. When an overridden method is called from within a sub class, it always refer to version of that method defined by super class will be hidden.

Example of Method Overriding or Run-time Polymorphism:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication16 {   class A    { int i, j;

public A(int a, int b)       { i = a;           j = b;        } public virtual void show {           Console.WriteLine(" i and j= {0} {1}", i, j); }   }    class B : A    { int k;       public B(int a, int b, int c)            : base(a, b)        { k = c;       } public override void show {           Console.WriteLine("k={0}", k); }   }

class Program {       static void Main(string[] args) {           A a;            B b;            a = new B(3,4,5); a.show; Console.ReadKey;

}   } }

Output: K=5

2.Datatypes And Variables

2.A.Data types: All types of c# are derived from a base class object. There are two types of data types. 1. Basic/build-in types(int,float,char) 2. User defined datatypes(class,struct,interface)

Integral Types: They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. Type 	Size (in bits) 	Range sbyte 	8 	-128 to 127 byte 	8 	0 to 255 short 	16 	-32768 to 32767 ushort 	16 	0 to 65535 int 	32 	-2147483648 to 2147483647 uint 	32 	0 to 4294967295 long 	64 	-9223372036854775808 to 9223372036854775807 ulong 	64 	0 to 18446744073709551615 char 	16 	0 to 65535 Floating Point and Decimal Types: A C# floating point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values. Type 	Size (in bits) 	precision 	Range float 	32 	7 digits 	1.5 x 10-45 to 3.4 x 1038 double 	64 	15-16 digits 	5.0 x 10-324 to 1.7 x 10308 decimal 	128 	28-29 decimal places 	1.0 x 10-28 to 7.9 x 1028 The string Type: A string is a sequence of text characters. The Boolean Type: Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, Boolean conditions can be satisfied where 0 means false and anything else means true. Memory allocation of the data type divides them into two types: 1. Value types(Which stores values):                                                            i)All basic or build-in types except strings                                                  ii)structs                                                                                                               iii)Enumeration(Enum types)							                             2.Reference types(which store references to the actual data)	:             i)class                                                                                                                ii)interface                                                                                                       iii)delegates                                                                                              iv)string                                                                                                         v)object 2.B.Character Escape Sequences: Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. Escape Sequence 	Meaning \' 	Single Quote \" 	Double Quote \\ 	Backslash \0 	Null, not the same as the C# null value \a 	Bell \b 	Backspace \f 	form Feed \n 	Newline \r 	Carriage Return \t 	Horizontal Tab \v 	Vertical Tab C# Operators: Category (by precedence) 	Operator(s) 	Associativity Primary 	x.y f(x)  a[x]  x++  x--  new  typeof  default  checked  unchecked delegate 	left Unary 	+  -  !  ~  ++x  --x  (T)x 	right Multiplicative 	*  /  % 	left Additive 	+  - 	left Shift 	<<  >> 	left Relational 	<  >  <=  >=  is as 	left Equality 	==  != 	right Logical AND 	& 	left Logical XOR 	^ 	left Logical OR 	| 	left Conditional AND 	&& 	left Conditional OR 	|| 	left Null Coalescing 	?? 	left Ternary 	?: 	right Assignment 	=  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=  => 	right Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left. 2.C.The Array Type: Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size. C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages there are, however, a few differences that you should be aware of. When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.

int[] table; // not int table[];

Declaring Arrays: C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The following examples show how to declare different kinds of arrays: Single-dimensional arrays: int[] numbers;                                Multidimensional arrays:    string[,] names;                                                                                                                                                                                    Array-of-arrays (jagged):     byte[][] scores;                          	         Three-dimensional arrays:   int[,,] buttons=new int[4,5,3]; Example of Single-dimentional array: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 {   class Array {       static void Main(string[] args) {           int [] month_days; month_days=new int[12]; month_days[0]=31; month_days[1]=29; month_days[2]=31; month_days[3]=30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; Console.WriteLine("April has {0} days",month_days[3]); Console.ReadKey;

}   } } Output: April has 30 days Or using System;                                                                                                                    using System.Collections.Generic;                                                                                           using System.Linq;                                                                                                                   using System.Text;                                                                                                                 namespace ConsoleApplication17 {   class AutoArray {       static void Main(string[] args) {           int [] month_days={31,29,31,30,31,30,31,31,30,31,30,31}; Console.WriteLine("April has {0} days",month_days[3]); Console.ReadKey; }   } } Output: April has 30 days Example of Twodimentional array: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 {   class TwoDArray {       static void Main(string[] args) {           int[,] twoD = new int[4, 5]; int i, j, k = 0; for (i = 0; i < 4; i++) {               for (j = 0; j < 5; j++) {

twoD[i, j] = k;                   k++; }           }            for (i = 0; i < 4; i++) {               for (j = 0; j < 5; j++) {                   Console.Write("{0} ",twoD[i, j]); }               Console.WriteLine; }

Console.ReadKey; }   } } Output:                                                                                                                  0 1 2 3 4                                                                                                                5 6 7 8 9                                                                                                              10 11 12 13 14                                                                                                    15 16 17 18 19 Example of jagged Array(Array of Arrays): using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication4 {   class Program {       static void Main(string[] args) {           int i, j, k;            int[][] jaggedAr = new int[4][]; jaggedAr[0] = new int[1]; jaggedAr[1] = new int[2]; jaggedAr[2] = new int[3]; jaggedAr[3] = new int[4]; k = 0; for (i = 0; i < 4; i++){ for (j = 0; j < i + 1; j++) {                   jaggedAr[i][j] = k;                    k++; }                                  }            for (i = 0; i < 4; i++){ for (j = 0; j < i + 1; j++) {                   Console.Write(jaggedAr[i][j] + " ");

}               Console.WriteLine; }           Console.ReadKey; }

} } Output: 0 1 2 3 4 5 6 7 8 9

One of the differences between jagged arrays, int[][] jaggedAr, and multi-dimension arrays, int TwoD[,], is that a multi-dimension array will allocate memory for every element of each dimension, whereas a jagged array will only allocate memory for the size of each array in each dimension that you define. Most of the time, you'll be using multi-dimension arrays, if you need multiple dimensions, and will only use jagged arrays in very special circumstances when you are able to save significant memory by explicitly specifying the sizes of the arrays in each dimension.

3.Control Statement-Selection

C# supports two selection statements: if and switch.

Syntax of if statement: If(condition) statement1; Else statement2;

Nested if example: If(i==10) { If(j<20) a=b; If(k>100) c=d; Else a=c; } Else a=d;

If-else-if Ladder syntax: If(condition) Statement; Else if(condition) Statement; Else if(condition) Statement; Else Statement

3.A.If-else Example:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication17

{   class IfElse {       static void Main(string[] args) {           int a,b,c; string opt; string i, j;           Console.WriteLine("Enter a"); i= Console.ReadLine; a = Int32.Parse(i); Console.WriteLine("Enter b"); j = Console.ReadLine; b = Int32.Parse(j);

Console.WriteLine("Enter the operator"); opt = Console.ReadLine;

if (opt == "+") c = a + b;           else if (opt == "-") c = a - b;           else if (opt == "*") c = a * b;           else c = a / b;

Console.WriteLine("Result={0}", c); Console.ReadKey; }   } }

Output:Enter a             5 Enter b             6 Enter the operator +             Result=11

3.B.Example of Switch statement:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 { class Switch {

static void Main(string[] args) {

int month = 4; string season; switch (month) {               case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; default: season = "Bogus month"; break; }           Console.WriteLine("April is in the {0}", season);

Console.ReadKey; }   } }

Output: April is in the Spring

3.C.C# Branching Statements: Branching statement 	Description break 	Leaves the switch block continue 	Leaves the switch block, skips remaining logic in enclosing loop, and goes back to loop condition to determine if loop should be executed again from the beginning. goto 	Leaves the switch block and jumps directly to a label of the form " :" return 	Leaves the current method. throw 	Throws an exception.

4.Control Statements – Loops

4.A.while loop Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 { class WhileLoop {   public static void Main {       int number = 0;

while (number < 10) {           Console.Write("{0} ", number); number++; }       Console.WriteLine; Console.ReadKey; } } }

Output:                                                                                                                 0 1 2 3 4 5 6 7 8 9 4.B.do loop Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 { class DoLoop {   public static void Main {       int number = 10;

do       { Console.Write("{0} ", number); number--;

}while (number > 0); Console.WriteLine; Console.ReadKey; } } }

Output:                                                                                                              10 9 8 7 6 5 4 3 2 1 4.C.Example of for loop: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication17 {

class ForLoop {       public static void Main {           for (int i = 0; i < 20; i++) {               if (i == 10) break;

if (i % 2 == 0) continue;

Console.Write("{0} ", i); }           Console.WriteLine; Console.ReadKey; } } }

Output:                                                                                                                 1 3 5 7 9 The foreach Loop: A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace.

4.D.Example of foreach loop:

using System; using System.Collections.Generic;

using System.Linq; using System.Text;

namespace ConsoleApplication17 {

class ForEachLoop {       public static void Main {           string[] names = { "Rahul", "Amit", "Sumit", "Kunal" };

foreach (string person in names) {               Console.WriteLine("{0} ", person); } Console.ReadKey; } } }

Output:                                                                                                              Rahul                                                                                                                         Amit                                                                                                                          Sumit                                                                                                                           Kunal

5.Namespace The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types. System.Console.WriteLine(“Hello World!”);

System is a namespace and Console is a class in that namespace. The using keyword can be used so that the complete name is not required, as in the following example: using system; Console.WriteLine(“Hello World!”);

5.A.Example of namespace:

//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text;

namespace Example1 {

class NamespaceExample {       public static void Main {           System.Console.WriteLine("This is the new c# namespace example"); System.Console.ReadKey; }   } }

Output:                                                                                                               This is the new c# namespace example Example of nested namespace:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace Example {

namespace Example1 {       class NamespaceExample {           public static void Main {               Console.WriteLine("This is the new c# nested namespace example 1"); Console.ReadKey; }       }    } }

Output: This is the new c# nested namespace example 1

Or using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace Example.Example1 {       class NamespaceExample {           public static void Main {               Console.WriteLine("This is the new c# nested namespace example 2"); Console.ReadKey; }       } }

Output: This is the new c# nested namespace example 2

5.B.Namespace example using Directive:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Example.Example1;

class UsingDirective {           public static void Main {               myexample.print; }       }        namespace Example.Example1 {           class myexample {

public static void print {                   Console.WriteLine("Emaple using Directive"); Console.ReadKey; }           }        }

Output:Example using Directive

6.Introduction to Classes Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces. Every class has a constructor.

6.A.Constructor:Constructor is a class member function that execute automatically whenever an object is created of the class. Constructor has the same name as class and it has no return type not even void. This is because the implicit return type of a class’ constructor is the class itself.

6.A.i).Default Constructor: Constructor with no parameter is called Default Constructor.

6.A.ii).Parameterized Constructor: Constructor that accepts arguments is known as parameterized constructor.

6.A.iii).Static Constructors: C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor). Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster. Static constructors are used to initializing class static data members. Point to be remembered while creating static constructor: 1. There can be only one static constructor in the class. 2. The static constructor should be without parameters. 3. It can only access the static members of the class. 4. There should be no access modifier in static constructor definition. 6.A.iv).Copy Constructor: If you create a new object and want to copy the values from an existing object, you use copy constructor. This constructor takes a single argument: a reference to the object to be copied. Exaple of Default Constructor:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   class Box {       double width; double height; double depth; public Box {           width = 10; height = 10; depth = 10; }       public double volume {           return width * height * depth; }   }    class DefaultConstructor {       static void Main(string[] args) {           Box mybox=new Box; double vol; vol=mybox.volume; Console.WriteLine("Volume is {0}",vol); Console.ReadKey; }   }

}

Output:Volume is 1000

Example of Parameterized Construcutor:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   class Box {       double width; double height; double depth; public Box(double w,double h,double d)       { width = w;           height = h;            depth = d;        } public double volume {           return width * height * depth; }   }    class ParaConstructor {       static void Main(string[] args) {           Box mybox=new Box(10,20,15); double vol; vol=mybox.volume; Console.WriteLine("Volume is {0}",vol); Console.ReadKey; }   }

}

Output:Volume is 3000 Example of Static Constructor: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   public class test {       static string name; static int age; static test {           Console.WriteLine("Using static constructor"); name = "Depak Kumar"; age = 23; }       public static void display {           Console.WriteLine("Using static function"); Console.WriteLine(name); Console.WriteLine(age); }   }    class StaticConstructor {       static void Main(string[] args) {           test.display; Console.ReadLine; }   }

} Output:                                                                                                         Using static constructor                                                                              Using static function                                                                                    Depak kumar                     					                                                  23 Example of Copy Constuctor: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   public class test {       int x;        string y;        public test {           x = 5; y = "Hello"; }       public test(int a, string s)        { x = a;           y = s;        } public test(test obj) {           x = obj.x;            y = obj.y;        } public void show {           Console.WriteLine(x); Console.WriteLine(y); }   }    class CopyConstructor {       static void Main(string[] args) {           test obj1 = new test; test obj2 = new test(8,"world"); test obj3=new test(obj2); obj3.show; Console.ReadLine; }   }

} Output:                                                                                                                 8                                                                                                                                             world

7.Properties In C#, properties are nothing but natural extension of data fields. They are usually known as 'smart fields' in C# community. We know that data encapsulation and hiding are the two fundamental characteristics of any object oriented programming language. In C#, data encapsulation is possible through either classes or structures. By using various access modifiers like private, public, protected, internal etc it is possible to control the accessibility of the class members. Usually inside a class, we declare a data field as private and will provide a set of public SET and GET methods to access the data fields. This is a good programming practice, since the data fields are not directly accessible outside the class. We must use the set/get methods to access the data fields. Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. Another benefit of properties over fields is that you can change their internal implementation over time. 7.A.Example of Properties: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   class MyClass {       private int x;        public int X        { get {               return x;            } set {               x = value; }       }    }    class PropertiesExample {       static void Main(string[] args) {           MyClass mc = new MyClass; mc.X = 10; int xVal = mc.X;           Console.WriteLine(xVal); Console.ReadLine; }   }

} Output:10 7.B.Static Properties: C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also. using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {

class MyClass {       private static int x;        public static int X        { get {               return x;            } set {               x = value; }       }    }    class MyClient {       public static void Main {           MyClass.X = 10; int xVal = MyClass.X;           Console.WriteLine(xVal); Console.ReadLine; }   } } Output:10 7.C.Properties & Inheritance: The properties of a Base class can be inherited to a Derived class. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {

using System; class Base {       private int x;        public int X        { get {               Console.Write("Base GET "); return x;           } set {               x = value;

}       }    }    class Derived : Base {   }    class MyClient {       public static void Main {           Derived d1 = new Derived; d1.X = 10; Console.WriteLine(d1.X); Console.ReadLine; }   } }

Output: Base GET 10

7.D.Properties & Polymorphism: A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication18 {   class Base {  private int x;        public virtual int X        { get {               Console.Write("Base GET"); return x;           } set {               x=value ; Console.Write("Base SET"); }       }    }    class Derived : Base {  private int x;        public override int X        { get {               Console.Write("Derived GET "); return x;           } set {               x = value; Console.Write("Derived SET "); }       }    }    class Mypropertiespoly {       public static void Main {           Base b1 = new Derived; b1.X = 10; Console.WriteLine(b1.X); Console.ReadLine; }   } } Output:Derived SET Derived GET 10 7.E.Abstract Properties:

A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors. If the abstract class contains only set accessor, we can implement only set in the derived class. Example: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication18 {   abstract class Abstract {  private int x;        public abstract int X        { get; set; }   }    class Concrete : Abstract {  private int x;        public override int X        { get {               Console.Write("GET "); return x;           } set {               Console.Write("SET "); x = value;

}       }    }    class AbstractProperties {       public static void Main {           Concrete c1 = new Concrete; c1.X = 10; Console.WriteLine(c1.X); Console.ReadLine; }   }

} Output:SET GET 10

8.Interfaces

8.A.Defination of Interface: An interface is not a class. It is an entity that is defined by the word interface. An interface has no implementation, it has only the signature or in the other words, just the definition of the methods without any body. Since c# does not support multiple inheritance but the interface has the ability to implement multiple inheritance. 8.B.Example of Interface: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication19 {   public interface one {       void method1; }   public interface two {       void method2; }   public class example : one, two {       void one.method1 {           Console.WriteLine("First Interface"); }       void two.method2 {           Console.WriteLine("Second Interface"); }   }

class Interface {       static void Main(string[] args) {           example e = new example; one o;           o = (one)e; o.method1; two t;           t = (two)e; t.method2; Console.ReadLine;

}   } }

Output:                                                   			                                                   First Interface                    							                         Second Interface

9.Abstract Class An abstract class is a special kind of class that cannot be instantiated. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Abstract classes have the following features: •	An abstract class cannot be instantiated. •	An abstract class may contain abstract methods and accessors. •	It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. •	A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Abstract methods have the following features: •	An abstract method is implicitly a virtual method. •	Abstract method declarations are only permitted in abstract classes. •	Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example: public abstract void MyMethod;

•	The implementation is provided by an overriding method, which is a member of a non-abstract class. •	It is an error to use the static or virtual modifiers in an abstract method declaration. Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax. •	It is an error to use the abstract modifier on a static property. •	An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier. An abstract class must provide implementation for all interface members. An abstract class that implements an interface might map the interface methods onto abstract methods. For example: interface I { void M; } abstract class C: I { public abstract void M; } 9.A.Example of Abstractclass: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   abstract class vechicle {       public abstract void speed; public abstract void maintainance; public abstract void value; }   class Fourwheeler:vechicle {       public override void speed {           Console.WriteLine("In Speed of Fourwheeler"); }       public override void maintainance {           Console.WriteLine("In Maintaunance of Fourwheeler"); }       public override void value {           Console.WriteLine("In Value of Fourwheeler"); }   }    class Twowheeler:vechicle {       public override void speed {           Console.WriteLine("In Speed of Twowheeler"); }       public override void maintainance {           Console.WriteLine("In Maintaunance of Twowheeler"); }       public override void value {           Console.WriteLine("In Value of Twowheeler"); }   }    class AbstractExample {

static void Main(string [] args) {           vechicle maruti, bajaj; maruti = new Fourwheeler; bajaj = new Twowheeler; maruti.speed; maruti.maintainance; maruti.value; bajaj.speed; bajaj.maintainance; bajaj.value; Console.ReadKey; }   } }

Output:                                                                                                  In Speed of Fourwheeler In Maintaunance of Fourwheeler In Value of Fourwheeler                                                                                                  In Speed of Twowheeler In Maintaunance of Twowheeler In Value of Twowheeler

9.B.Interface vs Abstract class: i) In Interface a class may inherit several interfaces. And In Abstract class a class may inherit only one abstract class. ii) An Interface cannot provide any code, it provides just the signature. Whereas an abstract class can provide complete default code and/or just the details that have to overridden. iii) An Interface cannot have access modifier for the subs, functions, properties, etc everything is assumed as public. Whereas an abstract class can contain access modifiers for the subs, functions, properties which can private, public or protected. iv) In Interface it requires more time to find the actual method in the corresponding class whereas An Abstract works probably fast.

10.Delegates and Events

Definition 1: A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Definition 2: A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer. However, developers who have used other languages are probably wondering, "Why do I need a reference to a method?". The answer boils down to giving you maximum flexibility to implement any functionality you want at runtime. Definition 3: A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example: public delegate int PerformCalculation(int x, int y); Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method. This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way. Delegates have the following properties: •	Delegates are similar to C++ function pointers, but are type safe. •	Delegates allow methods to be passed as parameters. •	Delegates can be used to define callback methods. •	Delegates can be chained together; for example, multiple methods can be called on a single event. •	Methods don't need to match the delegate signature exactly. •	C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method. 10.A.Example of Delegate:

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication20 {   public delegate int Comparer(object obj1, object obj2);

public class Name {       public string FirstName = null; public string LastName = null;

public Name(string first, string last) {           FirstName = first; LastName = last; }

// this is the delegate method handler public static int CompareFirstNames(object name1, object name2) {           string n1 = ((Name)name1).FirstName; string n2 = ((Name)name2).FirstName;

if (String.Compare(n1, n2) > 0) {               return 1; }           else if (String.Compare(n1, n2) < 0) {               return -1; }           else {               return 0; }       }

public override string ToString {           return FirstName + " " + LastName; }   }

class SimpleDelegate {       Name[] names = new Name[5];

public SimpleDelegate {           names[0] = new Name("Sumit", "Mandal"); names[1] = new Name("Saugata", "Bhandari"); names[2] = new Name("Sujit", "Mandal"); names[3] = new Name("Soumya", "Ghosh"); names[4] = new Name("Sayan", "Karmakar"); }

static void Main(string[] args) {           SimpleDelegate sd = new SimpleDelegate;

// this is the delegate instantiation Comparer cmp = new Comparer(Name.CompareFirstNames);

Console.WriteLine("\nBefore Sort: \n");

sd.PrintNames;

// observe the delegate argument sd.Sort(cmp);

Console.WriteLine("\nAfter Sort: \n");

sd.PrintNames; Console.ReadKey; }

// observe the delegate parameter public void Sort(Comparer compare) {           object temp;

for (int i = 0; i < names.Length; i++) {               for (int j = i; j < names.Length; j++) {                   // using delegate "compare" just like // a normal method if (compare(names[i], names[j]) > 0) {                       temp = names[i]; names[i] = names[j]; names[j] = (Name)temp; }               }            }        }

public void PrintNames {           Console.WriteLine("Names: \n");

foreach (Name name in names) {               Console.WriteLine(name.ToString); }       }    } }

Output:                               				                                                  Before Sort: Name: Sumit Mandal   						                                                  Saugata Bhandari       								                       Sujit Mandal                          							                      Soumya Ghosh                         				                               Sayan Karmakar After Sort: Name: Saugata Bhandari 						                                            Sayan Karmakar							                                            Soumya Ghosh    									    Sujit Mandal         						                                 Sumit Mandal Explanation Of the Above Program: The first thing this program is declarration of a delegate. Delegate declarations look somewhat like methods, except they have the delegate modifier, are terminated with a semi-colon, and have no implementation. Below, is the delegate declaration from: public delegate int Comparer(object obj1, object obj2); This delegate declaration defines the signature of a delegate handler method that this delegate can refer to. The delegate handler method, for the Comparer delegate, can have any name, but must have a first parameter of type object, a second parameter of type object, and return an int type. The following method shows a delegate handler method that conforms to the signature of the Comparer delegate. public static int CompareFirstNames(object name1, object name2) {       ...    } Note: The CompareFirstNames method calls String.Compare to compare the FirstName properties of the two Name instances. The String class has many convenience methods, such as Compare, for working with strings. Please don't allow the implementation of this method to interfere with learning how delegates work. What you should concentrate on is that CompareFirstNames is a handler method that a delegate can refer to, regardless of the code inside of that method. To use a delegate, you must create an instance of it. The instance is created, similar to a class instance, with a single parameter identifying the appropriate delegate handler method, as shown below. Comparer cmp = new Comparer(Name.CompareFirstNames); The delegate, cmp, is then used as a parameter to the Sort method, which uses it just like a normal method. Observe the way the delegate is passed to the Sort method as a parameter in the code below. sd.Sort(cmp); Using this technique, any delegate handler method may be passed to the Sort method at run-time. i.e. You could define a method handler named CompareLastNames, instantiate a new Comparer delegate instance with it, and pass the new delegate to the Sort method.

10.B.Events: A C# event is a class member that is activated whenever the event it was designed for occurs. I like to use the term "fires" when the event is activated. Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, registered methods will be invoked. Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.

10.C.Example of Events: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms;

namespace ConsoleApplication20 {   public delegate void Startdelegate;

class Eventdemo : Form {       // custom event public event Startdelegate StartEvent;

public Eventdemo {           Button clickMe = new Button;

clickMe.Parent = this; clickMe.Text = "Click Me"; clickMe.Location = new Point(               (ClientSize.Width - clickMe.Width) / 2,                (ClientSize.Height - clickMe.Height) / 2);

// an EventHandler delegate is assigned // to the button's Click event clickMe.Click += new EventHandler(OnClickMeClicked);

// our custom "Startdelegate" delegate is assigned // to our custom "StartEvent" event. StartEvent += new Startdelegate(OnStartEvent);

// fire our custom event StartEvent; }

// this method is called when the "clickMe" button is pressed public void OnClickMeClicked(object sender, EventArgs ea) {           MessageBox.Show("You Clicked My Button!"); }

// this method is called when the "StartEvent" Event is fired public void OnStartEvent {           MessageBox.Show("I Just Started!"); }

static void Main(string[] args) {           Application.Run(new Eventdemo); }   }

}

Output: Then Click ok Note: If you're using Visual Studio or another IDE, remember to add references to System.Drawing.dll and System.Windows.Forms.dll before compiling Listing 14.2 or just add the code to a Windows Forms project. You may have noticed that previous program is a Windows Forms program. Although I haven't covered Windows Forms in this tutorial, you should know enough about C# programming in general that you won't be lost. To help out, I'll give a brief explanation of some of the parts that you may not be familiar with. The Eventdemo class inherits Form, which essentially makes it a Windows Form. This automatically gives you all the functionality of a Windows Form, including Title Bar, Minimize/Maximize/Close buttons, System Menu, and Borders. The way a Windows Form's application is started is by calling the Run method of the static Application object with a reference to the form object as its parameter. This starts up all the underlying Windows plumbing, displays the GUI, and ensures that events are fired as appropriate. Let's look at the custom event first. Below is the event declaration, which is a member of the Eventdemo class. It is declared with the event keyword, a delegate type, and an event name. public event Startdelegate StartEvent;

Anyone interested in an event can register by hooking up a delegate for that event. On the next line, we have a delegate of type Startdelegate, which the event was declared to accept, hooked up to the StartEvent event. The += syntax registers a delegate with an event. To unregister with an event, use the -= with the same syntax. StartEvent += new Startdelegate(OnStartEvent);

Firing an event looks just like a method call, as shown below: StartEvent; This was how to implement events from scratch, declaring the event and delegate yourself. However, much of the event programming you'll do will be with pre-defined events and delegates. This leads us to the other event code you see in the previous program, where we hook up an EventHandler delegate to a Button Click event. clickMe.Click += new EventHandler(OnClickMeClicked); The Click event already belongs to the Button class and all we have to do is reference it when registering a delegate. Similarly, the EventHandler delegate already exists in the System namespace of the .NET Frameworks Class Library. All you really need to do is define your callback method (delegate handler method) that is invoked when someone presses the clickMe button. The OnClickMeClicked method, shown below, conforms to the signature of the EventHandler delegate, which you can look up in the .NET Framework Class Library reference. public void OnClickMeClicked(object sender, EventArgs ea) {       MessageBox.Show("You Clicked My Button!"); } Any time the clickMe button is pressed with a mouse, it will fire the Click event, which will invoke the OnClickMeClicked method. The Button class takes care of firing the Click event and there's nothing more you have to do. Because it is so easy to use pre-defined events and delegates, it would be a good idea to check if some exist already that will do what you need, before creating your own.

11.Exception Handling

Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. For example, validating user input, checking for null objects, and verifying the values returned from methods are what you expect, are all examples of good standard error handling that you should be doing all the time. An exception is an object that describes an exceptional condition (that is error) that has occurred in a piece of code. When a exception condition arises, an object representing that exception is created and thrown in the method that cause the error. That method may choose to handle the exception itself, or pass it on Either way, at some point, the exception is caught and processed. Exceptions can be generated by the run-time system or they can be manually generated by your code. C# Exception handling is manage by via four keywords:-try,catch,throw,finally. Program statements that you want to monitor for exception are contained within a try block. If an exception occurs within the try block, it is thrown, your code catch this exception (using catch) and handle it in some rational manner. System generated exception is automatically thrown by the java run-time system. To manually throw an exception, use the keyword throw. The System.Exception class provides several methods and properties for obtaining information on what went wrong. For example, the Message property provides summary information about what the error was, the Stacktrace property provides information from the stack for where the problem occurred, and the ToString method is overridden to reveal a verbose description of the entire exception. Identifying the exceptions you'll need to handle depends on the routine you're writing. For example, if the routine opened a file with the System.IO.File.OpenRead method, it could throw any of the following exceptions: •	SecurityException •	ArgumentException •	ArgumentNullException •	PathTooLongException •	DirectoryNotFoundException •	UnauthorizedAccessException •	FileNotFoundException •	NotSupportedException 11.A.Example Of Exception Handling: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class TryCatchDemo {       static void Main(string [] args) {           try {               int d = 0; int a = 42 / d;               Console.WriteLine("This will not be printed"); }           catch (ArithmeticException e)            { Console.WriteLine("Division by zero"); Console.WriteLine("After catch statement"); }             Console.ReadKey; }   } }

Output: Division by zero			                                                                  After catch statement

12.Enums Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast. Enums lend themselves to more maintainable code because they are symbolic, allowing you to work with integral values, but using a meaningful name to do so. For example, what type of code would you rather work with - a set of values named North, South, East, and West or the set of integers 0, 1, 2, and 3 that mapped to the same values, respectively? Enums make working with strongly typed constants via symbolic names easy. Enums are value types, which means they contain their own value, can't inherit or be inherited from, and assignment copies the value of one enum to another. You will see in this lesson and elsewhere that enums are used and referred to with both lower case, enum, and upper case, Enum. The relationship between the two is that the C# type, enum, inherits the Base Class Library (BCL) type, Enum. Use the C# type, enum, to define new enums and use the BCL type, Enum, to implement static enum methods. 12.A.Example Of Enums: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication20 {   public enum Volume {       Low, Medium, High }

// demonstrates how to use the enum

class EnumSwitch {       static void Main {           // create and initialize // instance of enum type Volume myVolume = Volume.Medium;

// make decision based // on enum value switch (myVolume) {               case Volume.Low: Console.WriteLine("The volume has been turned Down."); break; case Volume.Medium: Console.WriteLine("The volume is in the middle."); break; case Volume.High: Console.WriteLine("The volume has been turned up."); break; }           Console.ReadLine; }   } }

Output: The volume is in the middle.

13.Operator Overloading An operator may exhibit different behavior depends upon the type of the data are used in the operation. For example for addition operation two operators produce a sum by addition. If the operators are two strings then the two string produce a third string by concatenation. The process of making operator that exhibit different behavior in different instance are called operator overloading. The following set of operators is commonly overloaded for user-defined classes: •	= (assignment operator) •	+ - * (binary arithmetic operators) •	+= -= *= (compound assignment operators) •	== != (comparison operators) 13.A.Example Of Binary Operator: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class BOperation {       int data; string s;       public void getdata {           Console.WriteLine("Enter the numbers"); s=Console.ReadLine; data = Int32.Parse(s); }

static public BOperation operator +(BOperation x, BOperation y)       { BOperation result=new BOperation; result.data = x.data + y.data; return result; }       static public BOperation operator -(BOperation x, BOperation y)        { BOperation result = new BOperation; result.data = x.data - y.data; return result; }       static public BOperation operator *(BOperation x, BOperation y)        { BOperation result = new BOperation; result.data = x.data * y.data; return result; }       static public BOperation operator /(BOperation x, BOperation y)        { BOperation result = new BOperation; result.data = x.data / y.data; return result; }       public void show {           Console.WriteLine("{0}", data); }   }    class example {       static void Main(string[] args) {           BOperation obj1 = new BOperation; BOperation obj2 = new BOperation; BOperation obj3 = new BOperation; obj1.getdata; obj2.getdata; obj3 = obj1 + obj2; Console.WriteLine("Result of Addition:"); obj3.show; obj3 = obj1 - obj2; Console.WriteLine("Result of Substraction:"); obj3.show; obj3 = obj1 * obj2; Console.WriteLine("Result of Multiplication:"); obj3.show; obj3 = obj1 / obj2; Console.WriteLine("Result of Division:"); obj3.show; Console.ReadLine;

}

} }

Output:											 Enter the numbers:				                                                                         8                                                                                                                                    Enter the numbers:				                                                                          4 Result of Addition:							                                      12   	                                                                                                                             Result of Subtraction:							                                       4                                                                                                                                 Result of Multiplication:							                                       32       						                                                       Result of Divition:							                                       2 13.B.Example of Unary Operator: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class UOperation {       int data; string s;       public void getdata {           Console.WriteLine("Enter the number"); s = Console.ReadLine; data = Int32.Parse(s); }       static public UOperation operator ++(UOperation x)        { UOperation result = new UOperation; result.data = x.data++; return result; }       static public UOperation operator --(UOperation x)        { UOperation result = new UOperation; result.data = x.data--; return result; }       public void show {           Console.WriteLine("{0}", data); }   }    class Unaryexample {       static void Main(string[] args) {           UOperation obj1 = new UOperation; UOperation obj2 = new UOperation; obj1.getdata; obj2 = obj1++; Console.WriteLine("Result of ++ operator:"); obj2.show; obj2 = obj1--; Console.WriteLine("Result of -- operator:"); obj2.show; Console.ReadLine;

}

} }

Output:	                                                                                                                    Enter  the number                                                                                                             20                                                                                                                             Result of ++ Operator                                                                                                 21  			                                                                                                          Result of -- Operator                                                                                                 19

14.Generic Collections

In .NET v1.0 there were collections, such as the ArrayList for working with groups of objects. An ArrayList is much like an array, except it could automatically grow and offered many convenience methods that arrays don't have. The problem with ArrayList and all the other .NET v1.0 collections is that  they operate on type object. Since all objects derive from the object type, you can assign anything to an ArrayList. The problem with this is that you incur performance overhead converting value type objects to and from the object type and a single ArrayList could accidentally hold different types, which would cause hard to find errors at runtime because you wrote code to work with one type. Generic collections fix these problems. A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object. With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems. Creating Generic List<T> Collections The pattern for using a generic List collection is similar to arrays. You declare the List, populate its members, then access the members. Here's a code example of how to use a List: List myInts = new List ;

myInts.Add(1); myInts.Add(2); myInts.Add(3); for (int i = 0; i < myInts.Count; i++) {	       Console.WriteLine("MyInts: {0}", myInts[i]); } The first thing you should notice is the generic collection List, which is referred to as List of int. If you looked in the documentation for this class, you would find that it is defined as List<T>, where T could be any type. For example, if you wanted the list to work on string or Customer objects, you could define them as List or List<Customer> and they would hold only string or Customer objects. In the example above, myInts holds only type int. Using the Add method, you can add as many int objects to the collection as you want. This is different from arrays, which have a fixed size. The List<T> class has many more methods you can use, such as Contains, Remove, and more. There are two parts of the for loop that you need to know about. First, the condition uses the Count property of myInts. This is another difference between collections and arrays in that an array uses a Length property for the same thing. Next, the way to read from a specific position in the List<T> collection, myInts[i], is the exact same syntax you use with arrays. The next time you start to use a single-dimension array, consider using a List<T> instead. That said, be sure to let your solution fit the problem and use the best tool for the job. i.e. it's common to work with byte[] in many places in the .NET Framework. Working with Dictionary<TKey, TValue> Collections Another very useful generic collection is the Dictionary, which works with key/value pairs. There is a non-generic collection, called a Hashtable that does the same thing, except that it operates on type object. However, as explained earlier in this lesson, you want to avoid the non-generic collections and use thier generic counterparts instead. The scenario I'll use for this example is that you have a list of Customers that you need to work with. It would be natural to keep track of these Customers via their CustomerID. The Dictionary example will work with instances of the following Customer class: public class Customer {       public Customer(int id, string name) {           ID = id; Name = name; }

private int m_id;

public int ID       { get { return m_id; } set { m_id = value; } }

private string m_name;

public string Name {           get { return m_name; } set { m_name = value; } }   }

The Customer class above has a constructor to make it easier to initialize. It also exposes its state via public properties. It isn't very sophisticated at this point, but that's okay because its only purpose is to help you learn how to use a Dictionary collection. The following example populates a Dictionary collection with Customer objects and then shows you how to extract entries from the Dictionary: Dictionary<int, Customer> customers = new Dictionary<int, Customer>;

Customer cust1 = new Customer(1, "Cust 1"); Customer cust2 = new Customer(2, "Cust 2"); Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1); customers.Add(cust2.ID, cust2); customers.Add(cust3.ID, cust3);

foreach (KeyValuePair<int, Customer> custKeyVal in customers) {       Console.WriteLine(            "Customer ID: {0}, Name: {1}",            custKeyVal.Key,            custKeyVal.Value.Name); } The customers variable is declared as a Dictionary<int, Customer>. Considering that the formal declaration of Dictionary is Dictionary<TKey, TValue>, the meaning of customers is that it is a Dictionary where the key is type int and the value is type Customer. Therefore, any time you add an entry to the Dictionary, you must provide the key because it is also the key that you will use to extract a specified Customer from the Dictionary.

I created three Customer objects, giving each an ID and a Name. I'll use the ID as the key and the entire Customer object as the value. You can see this in the calls to Add, where custX.ID is added as the key (first parameter) and the custX instance is added as the value (second parameter). Extracting information from a Dictionary is a little bit different. Iterating through the customers Dictionary with a foreach loop, the type returned is KeyValuePair<TKey, TValue>, where TKey is type int and TValue is type Customer because those are the types that the customers Dictionary is defined with. Since custKeyVal is type KeyValuePair<int, Customer> it has Key and Value properties for you to read from. In our example, custKeyVal.Key will hold the ID for the Customer instance and custKeyVal.Value will hold the whole Customer instance. The parameters in the Console.WriteLine statement demonstrate this by printing out the ID, obtained through the Key property, and the Name, obtained through the Name property of the Customer instance that is returned by the Value property. The Dictionary type is handy for those situations where you need to keep track of objects via some unique identifier. For your convenience, here's Listing 20-1, shows how both the List and Dictionary collections work. 14.A.Example of Generic Collections: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication21 {   public class Customer {       public Customer(int id, string name) {           ID = id; Name = name;

}

private int m_id;

public int ID       { get { return m_id; } set { m_id = value; } }

private string m_name;

public string Name {           get { return m_name; } set { m_name = value; } }   }

class GenericCollection {       static void Main(string[] args) {           List myInts = new List ;

myInts.Add(1); myInts.Add(2); myInts.Add(3);

for (int i = 0; i < myInts.Count; i++) {               Console.WriteLine("MyInts: {0}", myInts[i]); }

Dictionary<int, Customer> customers = new Dictionary<int, Customer>;

Customer cust1 = new Customer(1, "Cust 1"); Customer cust2 = new Customer(2, "Cust 2"); Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1); customers.Add(cust2.ID, cust2); customers.Add(cust3.ID, cust3);

foreach (KeyValuePair<int, Customer> custKeyVal in customers) {               Console.WriteLine(                    "Customer ID: {0}, Name: {1}",                    custKeyVal.Key,                    custKeyVal.Value.Name); }

Console.ReadKey; }   } }

Output:                 				                                                                MyInts: 1		                                                                                                   MyInts: 2                                                                                                                 MyInts: 3         	                                                                                                    Customer ID: 1, Name:  Cust 1                                                                        Customer ID: 2, Name:  Cust 2                                                                             Customer ID: 3, Name:  Cust 3

15.C# Type 15.A.Type Safety: In untyped languages, such as scripting languages, you can assign one variable to another and the compiler/interpreter will use an intelligent algorithm to figure out how the assignment should be done. If the assignment is between two variables of the same type, all is good. However, if the assignment is between different types, you could have serious problems. For example, if you assigned an int value to a float variable it would convert okay because the fractional part of the new float would just be zero. However, if you went the other way and assigned a float value to an int variable, that would most likely be a problem. You would lose all of the precision of the original float value. Consider the damage that could be caused if the float value represented a chemical ingredient, an engineering measurement, or a financial value. Finding such an error would be difficult and particularly expensive, especially if the error didn't show up until your application was in production (already being used by customers). Example of an implicit conversion, which doesn't require the cast operator, and an explicit conversion: using System;

class Program {   static void Main {       float lengthFloat = 7.35f;

// lose precision - explicit conversion int lengthInt = (int)lengthFloat;

// no problem - implicit conversion double lengthDouble = lengthInt;

Console.WriteLine("lengthInt = " + lengthInt); Console.WriteLine("lengthDouble = " + lengthDouble); Console.ReadKey; }

Output:                                                                                                           lengthInt = 7 lengthDouble = 7 Since a float, lengthFloat, has a fractional part but  an int, lengthInt, doesn't; the types aren't compatible. Because of type safety, C# won't allow you to assign lengthFloat directly to lengthInt, which would be dangerous. For your protection, you must use a cast operator, (int), to force the explicit conversion of lengthFloat to lengthInt. In the output, you can see that lengthInt is 7, showing that it lost the fractional part of the 7.35f value from lengthFloat. The assignment from lengthInt to lengthDouble is safe because a double is 64-bit and an int is 32-bit, meaning that you won't lose information. Therefore, the conversion is implicit, meaning that you can perform the assignment without the cast operator. 15.B.Understanding Reference Types: Reference type variables are named appropriately (reference) because the variable holds a reference to an object. In C and C++, you have something similar that is called a pointer, which points to an object. While you can modify a pointer, you can't modify the value of a reference - it simply points at the object in memory. An important fact you need to understand is  that when you are assigning one reference type variable to another, only the reference is copied, not  the object. The variable holds the reference and that is what is being copied. 15.C.Example of Reference Types: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   class Employee {       private string m_name;

public string Name {           get { return m_name; } set { m_name = value; } }   }

class ReferenceType {       static void Main {           Employee joe = new Employee; joe.Name = "Joe";

Employee bob = new Employee; bob.Name = "Bob";

Console.WriteLine("Original Employee Values:"); Console.WriteLine("joe = " + joe.Name); Console.WriteLine("bob = " + bob.Name);

// assign joe reference to bob variable bob = joe;

Console.WriteLine; Console.WriteLine("Values After Reference Assignment:"); Console.WriteLine("joe = " + joe.Name); Console.WriteLine("bob = " + bob.Name);

joe.Name = "Bobbi Jo";

Console.WriteLine; Console.WriteLine("Values After Changing One Instance:"); Console.WriteLine("joe = " + joe.Name); Console.WriteLine("bob = " + bob.Name);

Console.ReadKey; }   } }

Output:                                                   Original Employee Values: joe = Joe bob = Bob

Values After Reference Assignment: joe = Joe bob = Joe Values After Changing One Instance: joe = Bobbi Jo bob = Bobbi Jo

I created two Employee instances, joe and bob. You can see in the output that the Name properties of both Employee instances each show their assigned values from when the objects were first created. After assigning joe to bob, the value of the Name properties of both instances are the same. This is what you might expect to see. What might surprise you is the values that occur after assigning a value to the Employee instance variable named joe. If you look at the code closely, you'll notice that it doesn't change bob - only Joe. However, the results from the output show that the Name property in bob is the same as the Name property in joe. This demonstrates that after assigning joe to bob, both variables held references to the joe object. Only the reference was copied - not the object. This is why you see the results of printing Name in both joe and bob are the same because the change was on the object that they both refer to. 15.D.Understanding Value Types: Value type variables, as their name (value) suggests, hold the object value. A value type variable holds its own copy of an object and when you perform assignment from one value type variable to another, both the left-hand-side and right-hand-side of the assignment hold two separate copies of that value. 15.E.Example of Value Types: using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication21 {   struct Height {       private int m_inches;

public int Inches {           get { return m_inches; } set { m_inches = value; } }   }

class ValueType {       static void Main {           Height joe = new Height; joe.Inches = 71;

Height bob = new Height; bob.Inches = 59;

Console.WriteLine("Original Height Values:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches);

// assign joe value to bob variable bob = joe;

Console.WriteLine; Console.WriteLine("Values After Value Assignment:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches);

joe.Inches = 65;

Console.WriteLine; Console.WriteLine("Values After Changing One Instance:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches);

Console.ReadKey; }   } }

Output:                                                                Original Height Values: joe = 71 bob = 59

Values After Value Assignment: joe = 71 bob = 71

Values After Changing One Instance: joe = 65 bob = 71 In this example you can see that the Inches property of bob and joe are initially set to different values. After assigning joe to bob, a value copy

occurs, where both of the variables have the same value, but are two separate copies. To demonstrate value assignment results, notice what happens after setting joe to 65; The output shows that bob did not change, which demonstrates that value types hold distinct copies of their objects. The following types are value types: •	enum •	struct Note: All of the primitive types (int, char, double, etc.), except for string, are value types.

16.A.Reference Type and Value Type Differences: From the previous paragraphs, you might already see that there is a difference reference type and value type assignment. Reference types copy a reference to an object and value types copy the object. If you don't know this, then the effects can be surprising in your code when performing tasks such as making assignments and passing arguments to methods.