You are on page 1of 181

Index

Introduction to OOPS Oops Concept Introduction to C# Dot Net Framework Literals and Data Types Branching and Looping Constructor Inheritance Abstract Class Interface Delegates Events Structure Arrays Enumerator Collections Exception Handling Sealed Class Files Generics

Contents:

Introduction
Classes And Object

OOPS Concepts
Advantages

INTRODUCTION

Object-Oriented Programming allows programmers to use the same terminology to explain the business domain and the program.

OOP enables users to model real-world objects. Modeling means representing real-world objects as components.

Explanation
Before OOP, programmers used to creating computer applications using procedural-programming (or structureprogramming) In procedural- programming all the program functionality written in a few modules of code or maybe one module (depending on the program). These modules depend on one another and maybe if you change a line of code you will have to rewrite the whole module again and maybe the whole program. The introduction of OOP, solved lots of problems of procedural programming. In oops codes are written in independent parts called classes. Each program functionality is divided into classes. The assembly combines these classes to form a single program. Now if any changes has to be made then that particular or specific class is taken and necessary changes is to be made.

CLASS & OBJECT The single entity holding the data and methods is called a class. An Object is an instance of a class. Eg: Car is a class and engine is an object. People is a class and Mary is an object. A class is a plan from which many objects can be created.

Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template.

Paper Pattern is the Class And Shirt is the Object

OOPS CONCEPTS

Polymorphism Encapsulation

Abstraction
Inheritance

INHERITANCE
Inheritance creates a hierarchy of classes and helps you reuse the code of a parent class in a child class. A Class inherits the attributes and behavior of its parent class or superclass. Superclass: Base class: Parent class. Subclass: Derived class: Child class. The mechanism of constructing one class from an other class is called Inheritance.

Syntax: <<Access modifiers>> class <subclass name> extends <superclass name>

The Shape class is the parent class. Square, Rectangle, and Circle are derived classes that inherit from Shape. class declaration class child: parent class Square: Shape

Shape

Circle

Rectangle Triangle

ENCAPSULATION
Encapsulation hides internal implementation details from users. Internal details, such as data representation should not be accessible externally, this protects outside users from making internal changes. There is visibility to the functionalities offered by an object, and no visibility to its data. Encapsulation means hiding of non-essential details.

EXAMPLE
When a user selects a command from a menu in an application, the code used to perform the actions of that command is hidden from the user. A Customer may issue a check and now know how it is processed. The internal processing is hidden from the customer.

ABSTRACTION

Abstraction means representing of essential details.


An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation.

A Shape class, which is an abstract class. In the real world, you never calculate the area or perimeter of a generic shape, you must know what kind of geometric shape you have because each shape (eg. square, circle, rectangle, etc.) has its own area and perimeter formulas. People own savings accounts, checking accounts, credit accounts, investment accounts, but not generic bank accounts. In this case, a bank account can be an abstract class and all the other specialized bank accounts inherit from bank account.

Shape

Circle

Rectangle

Triangle

POLYMORPHISM
Polymorphism means one entity existing in multiple forms. The design principle used in this is the same message sent to different objects results in different behavior. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior.

EXAMPLE
All of them are shapes and as shapes their area and perimeter can be calculated; however, each shape calculates its area in a specialized way. In the same way Every key of a keyboard performs a specific action when a keystroke message is generated for that key. However, by using polymorphism, the same code with a small change can be used by different keys of the keyboard to trigger specific actions.

Shape

Circle
Area=3.14*r*r (r=Radius)

Rectangle
Area=H*W (H=height, W=width)

Square
Area=4*S*S (S=side)

Advantages
Enables the use of real-world modeling . - Any real world object is considered as an object. Promotes the reuse of code. -By the use of inheritance etc, coding in a single class can be used many times. Provides flexibility in the modification of an existing application . -If any changes in a single line code, only that specific class is taken and made necessary changes. Helps with the maintainability of code. -You can create classes for different types of organization. - This helps in maintaining data information separately.

Contents:
Introduction What Lead to C# Features in C# Characteristics in C#

C#
C# (pronounced "C sharp") is a programming language that is designed for building a variety of applications that run on the .NET Framework. C# is simple, powerful, type-safe, and object-oriented.

Delegates, Interface, Foreach Statements, Enumerations are few features in C# which lag in C++.
The first component oriented language in the C/C++ family

What lead C#
C/C++ Drawbacks: Poor type safety. High complexity of language. Memory leakage. Weak in consistency. Visual Basic Drawbacks: Truly not Object- Oriented. Also could not meet the requirements of World Wide Web. Java Drawbacks: Lacking in inter-operability with code of other languages. Truly Object-Oriented but does not feature like Operating Overloading.

Hence keeping in view of these drawbacks, The Microsoft wanted new language that will suite the requirements of World Wide Web Application. Hence, Lead to the Introduction of c#( pronounced "C sharp").

Productivity of Visual Basic, Power of C++ and Elegance of Java combines to form C#. C# is the combination of 70% of Java, 10% of C++, 5% of Visual Basic and 15% new features.

New Features: Boxing/UnBoxing.


For each Statements. Go to. Events Delegates Interfaces Rectangular Arrays

Characteristics of c#: Object Oriented


Garbage Collection Namespace Data Types Inter Operability Versionable Security

Indexes

Exception Handling Data Types

Contents:
Introduction DotNet Architecture Common Language Runtime Base Class Library DotNet Framework Services DotNet Execution Model C# and DotNet

Dot Net Framework

C# is mainly dependent for supporting the key features of dot net framework.
The dot net framework provides an environment for building, deploying and running web services and other applications. This is the working platform for applications.

Dot Net Framework Architecture

VB

C++

C#

JAVA

Common Language Specification ASP. NET Web forms, Web Services ADO.NET and XML

Window Forms

Visual Studio Dot NET

Base Class Library

Common Language Runtime

Common Language Runtime

Common Language Runtime: -its a runtime engine which manages the runtime code (c# application). -is a part of dot net framework. Simplify Application Development, Deployment and Management. Managed code: -a code that satisfies the CLR.

Common Language Runtime

Program written in any DOT NET language (C#,VB.Net etc) Compiler Intermediate Language (IL) (.exe or .dll) Compiler Common Language Runtime Loads and Executes code

Common Type System: -Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other. -is responsible for interpreting the data types into the common format - e.g. how many bytes is an integer.

Common Language Specification: -This ensure inter-operability between Languages. -All the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS.

IL Compiler: -takes in the IL code and converts it to the host machine language. Security: -ensures that the assembly (the program being executed) has permissions to execute certain functions. Garbage collector: -Its function is to reclaim the memory when the object is no longer in use, this avoids memory leaks and dangling pointers. Class loader: -Its sole purpose is to load the classes needed by the executing application.

.Net Framework Services


ASP.NET: -Its a server side scripting technology. Web Forms: -Manageable code Window Forms: -Framework for building rich controls.

ADO.Net: -Used as connectivity( e.g.: datasets) -XML support.

.NET Base Class Libraries


System.Web
Services Description Discovery Protocols Caching Configuration Security SessionState Imaging UI HtmlControls WebControls Design

System.WinForms
ComponentModel

System.Drawing
Drawing2D Printing Text

System.Data
ADO Design SQL SQLTypes XSLT XPath

System.Xml
Serialization

System
Collections
Configuration Diagnostics Globalization IO Net Reflection Resources Security ServiceProcess Text Threading Runtime InteropServices Remoting

Serialization

Base Class Library


The Framework Class Library or FCL nothing short of a massive collection of classes, structures, enumerated types and interfaces defined and implemented for reuse in your managed software. If you like, you can use it like any other library. That is to say that you can write applications that make use of the objects in the Base Class Library to read files, display windows, and do various tasks. The FCL is a class library; however it has been designed for extendibility and compose ability. This is advanced reuse.

Visual Studio .NET


Visual Studio is an integrated

Manage and Collaborate

development environment published by Microsoft for writing Windows programs. .NET can also be used to write managed applications in C#, C++, Visual Basic and any other language

Planning Analysis

Design
Development Testing Deployment

Visual Studio .NET and the .NET Framework as different products.

.NET Platform

.Net Execution
C++ complier assembly

Source code

VB complier

C# complier assembly

Compilation

MSIL

assembly

Common Language Runtime / Just-In-Time Complier


Execution

Native

code

Managed code
CLR Service

Managed code

Managed code

Unmanaged code

Operating system service

Assembly: -Logical unit of deployment, also contains metadata, MSIL and resources. Microsoft Intermediate Language (MSIL or IL): -CPU independent language. Metadata: -Structured Information (class or method definition, properties etc). Managed Code: -Any code that targets the CLR. -Any .Net Language ,including c# ,c++, Visual Basic etc. JIT-Complier: -All managed code runs in native Language. Operating System: -your working system.

Sample
using System; //Namespace declaration class Sample //class Declaration { static void Main() //method { Console.write(Hello); } } OUTPUT: Hello The compilation saved with .cs extension which in this case is Sample.cs
Namespace: -elements designed to help you organize the program. -avoid clashes between two sets of code. Class Declaration: -contains data and methods definition that you use in your program. Method: -It tells what this class will do when executed. -Main, is always considered as entry point. Outlet: -console is a class in system namespace. -and write is a method in console class. -the (.)separates subordinate elements. -namespace.class.method=pattern

Contents:

Literals
Data Types

Reference And Value Type


Boxing And Unboxing

Literals
Literals are value constants assigned to variables .C# supports several types of literals. Boolean

True or False
String Sequence of Character. Eg: HELLO. Character

Literals

Boolean

Single Character, Simple-escape Sequence like below


Eg: a , \a \ \r \ Real Decimal Digits, Sign like +,-.
Character Integer

Integer
Decimal Digits, Hexadecimal Digits like below 0123456789abcdefABCDEF
Real String

Data Types
Integer: Int , uint 32-bit, Long , ulong 64-bit, Short , ushort 16-bit, Sbyte , byte 8-bit. Floating Point: Float 32-bit, Double 64 bit. Charactar and String: Char 16-bit unicode String-set of unicode

Type Conversion
int i = 5; double d = 3.2; string s = 432;

Implicit conversion
Cast required Conversion required

d = i;
i = (int)d;

i = System.Convert.Toint32(s);

Value And Reference Type


Value Type Directly contain data. Allocated on Stack. Eg: Structs,Enums Reference Type Contains reference to object. Allocated on Heap using new keyword. Eg: Classes,Interface Ex: object ob=a

Ex:

int a=1;

Boxing And UnBoxing


Converting value type to reference type is called Boxing. Converting reference to value type is called UnBoxing.

Eg: int a=1; //boxing object ob=a; int j=(int)ob; //unboxing

Contents:

Methods Kinds of Methods Properties

Methods
Any class has methods and properties. These are the places where business logic or functionally is written and executed. Method is declared as: Return-type methodname ( Parameterslist ); Example: Int Addition(int x,int y){} Int--- Return-type Addition---methodname Int x,int y---parameters list

Kinds Of Methods
There are two kinds of method: Instance method: This method is called by creating object of that class which contains the method. Static Method: This method is called by the classname in which the method is located. We should use the keyword static for this method. Syntax: Classname.methodname(); We can declare the signature of the same method once again in the same class but with different parameters. The parameters should be different.This is called method overloading.

Methods
using Systems; class Intsmethod { void show() { int x=100; int y=200; Console.WriteLine(x); Console.WriteLine(y); } static void Main() { Intsmethod a=new Intsmethod(); a.show(); } } *100 200

using System; class Statemethod { static void show() { int x=100; int y=200; Console.WriteLine(x); Console.WriteLine(y); } static void Main() { Statemethod.show(); } } *100
200

Methods with Two Parameters


using System; class Twopara { void show(int a, int b) { Console.WriteLine(a); Console.WriteLine(b); } static void Main() { Twopara t=new Twopara(); t.show(200,300); } } Using System; Class Overloadmet { Void show(int a) { Console.WriteLine(a); } Void show(int a, int b) { Console.WriteLine(a); Console.WriteLine(b); } Static void Main() { Overloadmet o=new Overloadmet(); o.show(2); o.show(5,9); *2 } *5 } 9

*200 300

Properties
Properties provide added functionality to the .Net framework. In c# property consists of 1. Field Declaration 2. Accessor method(get and set methods) <acces_modifier> <return_type> <property_name> { get{} set{} } Get() is used to retrieve a field value and Set() is used to modify fields value. If you want to make the property read-only, omit the set block and to make it write only, omit the get block. This is a secured manner to pass the data.

Properties
Example: Using System; Class Propertyex { Public string id; Public string Idvalue { Get { Return value; } Set { id=value; } } Static void Main() { Propertyex pe=new Propertyex(); pe.id=007; String p=pe.id; Console.WriteLine(The Value is {0},p); } } OUTPUT: 007

Contents:
If-Else Statements Switch Statements While Statements Do-While Statements For Statements Foreach Statements

IF-Else Statements
1. 2. 3. The first Selection Statements if statement has three forms: Single Selection. If then - else Selection. Multi - case Selection.

Syntax: if( condition1 ) //statement else if( condition2 ) //statement else (condition) //statement

Class elseifsample { Static void Main() { Console.Writeline(WRITE A NUMBER); Int i=Convert.Toint32(Console.ReadLine()); If(i>0 && i<100) { Console.WriteLine(YOUR NUMBER IS {0},i); } Else if(i<0) { Console.WriteLine(YOUR NUMBER {0} IS NEGATIVE ,i); } Else if(i==0) { Console.WriteLine(YOUR NUMBER IS ZERO); } Else { Console.WriteLine(NUMBER OUT OF RANGE); } } }

OUTPUT:

WRITE A NUMBER 25 YOUR NUMBER IS 25

Switch Statements
The second Selection is Switch case statements The value is compared to each of case statements untill match is found. Syntax: switch( value ) case result1: statement1; break; case result2: statement1; break; default: statement1

Class SwitchState { static void Main() { string k; int i, j; Console.WriteLine(Select two numbers); i= Convert.ToInt32(Console.ReadLine()); j= Convert.ToInt32(Console.ReadLine()); Console.WriteLine(Select operator +,-,*); k= Convert.ToChar(Console.ReadLine()); switch (k) { case +: Console.WriteLine({0}+{1}={2},i , j,+(i+j)); break; case -: Console.WriteLine({0}-{1}={2},i ,j,+(i-j)); break; case *: Console.WriteLine({0}*{1}={2},i ,j,+(i*j)); break; default: Console.WriteLine(Invalid operator {0},k); break; } } }

Select two numbers 2 3 Select operator +,-,* + 2+3=5

While Statements
WHILE statements A WHILE loop will check a condition and then continues to execute a block of code as long as the condition is true.

Syntax:
while( condition ) { statement; }

WHILE Statement
Using System; Class whilestate { static void Main() { int i=0; while (i<10) { Console.Write({0} ,i); i++; } } }
OUTPUT:

0123456789

Do While Statements
DO WHILE statements In WHILE loop statements, if condition is false then the statement will not execute. But in DO WHILE statement, first the statement in the block of code executes at least once then checks the condition. Syntax: do { statement; }while( condition );

DO WHILE Statements Class dowhilestate OUTPUT: { static void Main() { int i=0; 0123456789 do { System.Console.Write({0} ,i); i++; } while (i<10); } }

For Statement
FOR statements The for loop works like a while loop, except that the syntax of for loop includes initialization and condition. The for loop syntax explains clearly. The contents in the syntax is separated by semicolons.

Syntax:
For( initialization; condition; iterator ) { statement; }

For Statements
Class forstate { static void Main() { int i=0; for(int k=0;k<10;k++) { System.Console.Write({0} ,i); i++; } } }

OUTPUT:

0123456789

Foreach Statement
FOREACH statements This is similar to for statement. The foreach loop is used to iterate through items in the list. This is used for arrays or collection such as arraylist.

Syntax:

foreach( datatype varname in arrayname) { statement; }

Foreach Statement
Using System; Class foreachstate { static void Main() { int[] number={0,1,2,3,4,5,6,7,8,9}; foreach(int line in number) { Console.Write({0} ,line); } } } OUTPUT:

0123456789

Contents:

Introduction Static Constructor Overloaded Constructor Copy Constructor

CONSTRUCTOR
Constructor is a special method, evoked automatically whenever object is created. The class and the method both has same name. It has no return type. The are four types of constructors: Static Constructor Overloaded Constructor Copy constructor Default Constructor
} Object of the class can be created by using the new keyword. E.g: Myclass m=new Myclass Constructors can be declared "private or protected but commonly public is used. Syntax: class Myclass { public Myclass { }

1. 2. 3. 4.

Simple Constructor
class Cons { int length, height; public Cons ( int a, int b) { length=a; height=b; } public int area () { return a*b; } } class Class1 { public void Main() { Cons c=new Cons ( 3,4); int n=c.area(); Console.WriteLine( The area is = +n); } }
OUTPUT

The area is = 12

Static Constructor
Gets called before the first object is created of the class

It is used to perform an action only once. Keyword static is used. It does not contain any access modifier,no parameters. There can be only one static constructor in the class.

Syntax: class Sample { static Sample //static constructor {

}
}

OUTPUT:

class State { static State() { Console. WriteLine (This is one); } public void static land() { Console. WriteLine (This is two); } } class Sample { static void Main() { State. land(); State. land(); } }

*This is one This is two *This is two

Overloaded Constructor
constructors with different set of parameters
Eg: class Load { public Load() { Console. WriteLine (No Arguments in this method); } public Load( int i ) { Console. WriteLine (The number is {0}, I ); } public Load( int i, int j) { Console. WriteLine ({0}+{1}={2}, i ,j ,+(i+j)); } }

class Sample { static void Main() { Load o=new Load(); Load o1=new Load(6); Load o2=new Load(2,3); } } OUTPUT:

No Arguments in this method The number is 6 2+3=5

Copy Constructor
A copy constructor is a special constructor used to create a new object as a copy of an existing object.
Eg: class Person { private int age; private string name; public Person (Person p) //copy constructor { age =p. age; name=p. name; } public Person (int age, string name) //instance { //constructor this. age= age; this. name= name; } public string Details //get details { get { return name + is +age. Tostring(); } } }

Class Sample { static void Main() { Person h=new Person(23,Ram); Person h1=new Person (h); Console. WriteLine(h. Details); Console. WriteLine(h1. Details); } }
OUTPUT:

Ram is 23 Ram is 23

Destructor
In simple terms a destructor is a member that implements the actions required to destruct an instance of a class. Opposite to a constructor.

Syntax: ~ classname() { statement; }

Contents:

Introduction
Simple Inheritance

Multilevel Inheritance
Hierarchical Inheritance

Using Keywords

Inheritance
Access Modifier public---visible to every code private---visible only inside that class protected--- visible only to its class and derived type internal----visible inside the assembly protected internal---within the assembly and its derived type . Syntax: Class derivedClass:baseClass (deriving from base class) { } If a function or a property in the base class is declared as virtual it can be overridden in any derived classes The new keyword should be used when we intend to hide a method.

Types of Inheritance

1. 2. 3. 4.

The mechanism of designing or constructing one class from another is called inheritance. One class acquiring property of another class. There are four types of inheritance Single Inheritance Hierarchical Inheritance A Multiple Inheritance Single Multilevel Inheritance

Multiple A C B

Multilevel A
B C B

B
Hierarchical A B

C# does not support Multiple Inheritance.

Simple Inheritance
class Animal { public void name() { Console.WriteLine("This is Animals World"); } public void type() { Console.WriteLine("There are many types"); } public void size() { Console.WriteLine("There are are big animals"); } }
class Cat : Animal { public void kitty() { Console.WriteLine(" THis is a Cat"); } } class Simpleinherit { static void Main() { Cat c = new Cat(); c.kitty(); c.name(); This is a Cat. c.size(); c.type(); This is animals World. } There are big animals. }

There are many types

Multilevel
class Base { public virtual void who() { Console.WriteLine("This is who from Base Class"); } } class Derived : Base { public override void who() { Console.WriteLine("This is who from Derived Class"); } } class Derived1 : Derived { } class Derived2 : Derived1 { }

class Multilevel { static void Main() { Derived2 d2 = new Derived2(); Base b1 = new Base(); b1.who(); } }

This is Who from Derived Class

Hierarchical
public class Shape { public double area; public Shape() { area=0.0; } public void display( string name, double a) { Console. WriteLine(The area of + name + is +a); } } public class Square: Shape { int side; public Square( int s) { side=s; } public void calculatearea1() { area= 4*s*s; } } public class Circle: Shape { int radius; public Circle (int r) { radius=r; } public void calculatearea2() { area=3.14*r*r; } } class Sample The area of square is 100 { The area of circle is 78.5 static void Main() { Square s=new Square(5); s.calculatearea1(); s. display (square,s.area); Circle c=new Circle(5); c.calculatearea2(); c. display(circle,c.area); } }

OUTPUT:

Using Keywords
class Animal { public Animal() { Console.WriteLine("Animal constructor"); } public void Greet() { Console.WriteLine("Animal says Hello"); } public void Talk() { Console.WriteLine("Animal talk"); } public virtual void Sing() { Console.WriteLine("Animal song"); } }
class Dog : Animal { public Dog() { Console.WriteLine("Dog constructor"); } public new void Talk() //Hiding Methods using new keyword { Console.WriteLine("Dog talk"); } public override void Sing() { Console.WriteLine("Dog song"); } OUTPUT: } Class Mainclass { static void Main() Animal constructor { Dog constructor Dog d1 = new Dog(); Dog talk d1.Talk(); Dog song d1.Sing(); Animal says Hello d1.Greet(); } }

Contents:

Introduction Abstract Method Non-Abstract Method Partial-Implementation Using Interface

Abstract Class
An abstract class is a type of class that allows inheritance but can never be instantiated. An abstract class contains abstract and non-abstract methods. They contain one or more abstract method that do not have implementation. Abstract method do not have method body, they are implicitly virtual. Non-Abstract method contain method body. They provide only Partial Implementation. This is done by declaring the derived class as abstract class, we can avoid implementing of all or certain abstract methods. An abstract class can also implement from interface. In this method body should be provided while implementing from interface.

Abstract Method
class Baseclass { public void basemethod() { Console.WriteLine(This is Base method); } } abstract class Abclass:Baseclass { public void absmethod(); } class Subclass:Absclass { public override void absmethod() { Console.WriteLine(This is Abs method); } }

class Mainclass { static void Main() { Subclass s=new Subclass(); s.basemethod(); s.absmethod(); } } OUTPUT:

This is Base method This is Abs method.

Non-Abstract Method
abstract class nonabs { public void nonabsmethod() { Console.WriteLine(This is non abstract method); } } class Subclass:nonabs { } class Mainclass { static void Main() { Subclass s=new Subclass(); s.nonabsmethod(); } }

OUTPUT:

This is non abstract method

Using Interface
interface Interclass { void intermethod() } abstract class Abclass:Interclass { public void intermethod() { Console.WriteLine(This is Inter method); } public abstract void absmethod(); } class subclass:Absmethod { public abstract void absmethod() { Console.WriteLine(This is Abs method); } }

class Mainclass { static void Main() { Subclass s=new Subclass(); s.absmethod(); s.intermethod(); } } OUTPUT:

This is Inter method. This is Abs method.

Partial Implementation
abstract class Baseclass { public abstract void absmethod1(); public abstract void absmethod2(); } abstract class Subabs:Baseclass { public override void absmethod1() { Console.WriteLine(This is Base absmethod 1); } } class Subclass:Subabs { public override void absmethod2() { Console.WriteLine(This is Subabs abmethod 2); } }

class Mainclass { static void Main() { Subclass s=new Subclass() s.absmethod2(); s.absmethod1(); } } OUTPUT:

This is Sub absmethod 2. This is Base absmethod 1.

Contents: Introduction Single-Cast Delegate Multi-Cast Delegate

DELEGATES
Delegate is type which holds the method(s) reference in an object. It is also referred as a type safe function pointers. Declaration: public delegate type_of_delegate delegate_name() Example : public delegate int mydelegate(int delvar1,int delvar2) if you are referring the method with two int parameters and int return type the delegate which you are declaring should be the same format. This is how it is referred as type safe function pointer . If the delegate contains a return type of void, then it is automatically aliased to the type of System.MulticastDelegate.

If the delegate contains a non-void return type then it is aliased to System.Delegate class and it cannot support multiple methods. In C#, delegates act as an intermediary between an event source and an event destination. Eg: A group of people representing a company. What if you want to call three methods when a button is clicked?.At this point of time we use multi-cast Delegate .

Single Cast
public delegate double TestDelegate(int a,int b); class Class1 { static double Method1(int val1,int val2) { return val1*val2; } static void Main() { //Creating the Delegate Instance TestDelegate delObj = new TestDelegate(Method1); Console.Write("Please Enter Values"); int v1 = Int32.Parse(Console.ReadLine()); int v2 = Int32.Parse(Console.ReadLine()); //use a delegate for processing double res = delObj(v1,v2); Console.WriteLine ("Result :"+res) } }

OUTPUT:

Please Enter Values 3 6 Result:18

Multi-Cast
delegate void Multicast(); class Simplemulticast { static public void Method1() { Console.WriteLine("Your in Method1"); } static public void Method2() { Console.WriteLine("Your in Method2"); } static void Main() { Multicast m = new Multicast(Method1); Multicast m1 = new Multicast(Method2); m(); m1(); Multicast m2 = m + m1; m2(); } }

OUTPUT:

Your in Method1 Your in Method2 Your in Method 1 Your in Method2

Events
Events are the actions of the system on user manipulations(e.g. mouse clicks, key press, timer etc.) or any event triggered by the program. A large goal of design delegates is their applicability in events model of .Net. communication between event source and event receiver is called delegate. event source=objects that raise events. event receiver=object that responds to events. Ex: Speaking with a friend on phone. event source=you; event receiver=your friend; telephone=delegate;

// Delegate Declaration(<access><delegate><return type><delegate name>) public delegate void newdelegate(); // Event Declaration (<access><event><delegate name><event name>) public event newdelegate newevent;

Event method consists of procedure name followed by two arguments. The first argument is object firing and second is of System.EventArgs receiver. The += is used to hook up the event as a delegate i.e a method stand for another method.

class Myclass { public delegate void MyDelegate(string message); public event MyDelegate Myevent; public void RaiseEvent(string message) { if (Myevent != null) Myevent(message); } } class Event1 { static void Main() { Myclass c1 = new Myclass(); c1.Myevent += new Myclass.MyDelegate(c1_Myevent); Console.WriteLine("Please enter your msg here"); string msg = Console.ReadLine(); c1.RaiseEvent(msg); } static void c1_Myevent(string message) { Console.WriteLine("your message is {0}", message); } }

OUTPUT:

Please enter your msg here


Welcome to LST

Your message is Welcome to LST

Contents:
Introduction Simple Interface Explicit Interface Multiple Interface Inheriting from a class

Interface
C# does not support multiple inheritance. So, c# provides an alternative approach known as interface. An interface is a reference type object with no implementation. So the interface doesn't actually do anything but only has a signature for interaction with other classes or interfaces. It contains only definition, does not contain methods or properties code inside an interface. Syntax: private Class derivedClass:baseClass , InterfaceX , InterfaceY (deriving from interface) { }

Simple Interface
interface In1 //Interface1 { void show(); } interface In2 //Interface2 { void Display(); } class Interface1:In1,In2 //Simple inheritance { public void show() { Console.WriteLine("This is In1 Show method"); } public void Display() { Console.WriteLine("This is In2 Display method"); } static void Main() { Interface1 i = new Interface1(); i.Display(); i.show(); } }

OUTPUT:

This is In1 Show method. This is In2 Display method.

Explicit Interface
interface Int1 //Explicit interface Implementation { //Implementation of 2 methods of same name void show(); } interface Int2 { void show(); } class Interface2:Int1,Int2 { void Int1.show() { Console.WriteLine("This is Show from Int1"); } void Int2.show() { Console.WriteLine("This is Show from Int2"); } static void Main() { Interface2 l = new Interface2(); Int1 i1 = (Int1)l; i1.show(); Int2 i2 = (Int2)l; i2.show(); } } //casting //casting

OUTPUT:

This is Show from Int1. This is Show from Int2

Multiple Interface
interface Addition { int add(); } interface Multiplication { int mul(); } class Compare : Addition, Multiplication { int x, y; public Compare(int x, int y) { this.x = x; //Current value of X this.y = y; //Current value of y } public int add() { return x + y; } public int mul() { return x * y; } }

class Mulinterface { static void Main() { Compare c = new Compare(5, 5); Addition a = (Addition)c; //casting Console.WriteLine(a.add()); //create an instance of implementing class //and then cast the object to the interface Multiplication m = (Multiplication)c; //casting Console.WriteLine(m.mul()); } }
OUTPUT:

10 25

Inheriting a class
interface Display { void print(); } class B : Display { public void print() { Console.WriteLine("Base Display"); } } class C : B { public new void print() { Console.WriteLine("Derived Display"); } } class Inheritclass { static void Main() { C c1 = new C(); c1.print(); Display dis = (Display)c1; dis.print(); }

OUTPUT:

Derived Display Base Display

Contents: Introduction Simple Structs Using Method Using Interface Using Constructors

Structure
A C# structure is a value type The keyword struct can be used to declare a structure. Structure Declaration Syntax: <modifiers> struct <struct_name> { //Structure members } Remember that unlike classes, the strcut object can also be created without using the new operator. Like: MyStruct ms;

By default its private and therefore cannot be accessed outside the struct definition.
But static methods can access only other static members and they can't invoke by using an object of the structure. They can invoke only by using the struct name. Struct is not permitted to declare Structs, does not support default constructors. Since structs doesn't support inheritance, we can't use the keywords virtual, override, new, abstract etc with a struct methods. C# struct types are never abstract and are always implicitly sealed. The abstract or sealed modifiers are not permitted in a struct declaration

Simple & With Method

using System; struct MyStruct { public int x; public int y; } class MyClient { public static void Main() { MyStruct ms ; ms.x = 10; ms.y = 20; int sum = ms.x + ms.y; Console.WriteLine("The sum is {0}",sum); } } The sum is 30.

OUTPUT

using System; struct MyStruct { static int x = 25; static int y = 50; public void SetXY(int i, int j) { x = i; y = j; } public static void ShowSum() { int sum = x + y; Console.WriteLine("The sum is {0}",sum); } } class MyClient { public static void Main() { MyStruct ms = new MyStruct(); ms.SetXY(100,200); MyStruct.ShowSum(); } } OUTPUT

The sum is 300.

Interface & Constructor


using System; interface IInterface { void Method(); } struct Complex : IInterface { public void Method() { Console.WriteLine("Struct Method"); } } class MyClient { public static void Main() { Complex c1 = new Complex(); c1.Method(); } }

Output:

using System; struct MyStruct { int x ; int y ; public MyStruct(int i, int j):this(i+j) {} public MyStruct(int i) { x = y = i; } public void ShowXY() { Console.WriteLine("The field values are {0} & {1}",x,y); } } class MyClient { static void Main() { MyStruct ms1 = new MyStruct(10,20); The field values ms1.ShowXY(); Are 30&30. } } Output:

Struct Method

Contents: Introduction ArrayList HashTable Stack Queue

Collections
A collection in C# is a group of related objects held in a structure The .NET Foundation Class Library contains a namespace called System.Collections that provides classes to manage data structures like arrays, lists and maps. The ArrayList class is similar to the Array class except that its size can grow dynamically. The Queue and Stack classes provide the First In First Out and Last In First Out types of collections respectively.

ArrayList
Array is used to store only objects of same type, where as in arraylist we can store different types of objects which is stored as object type only. It uses its index to refer to an object in its collection. The Capacity property gets or sets the number of items that the ArrayList object can contain. You can Add an item by using Add() and remove an item using Remove() method.
using System; using System.Collections; class Collections1 { static void Main() { int i = 10; string g = "abc"; ArrayList a =new ArrayList(); a.Add("alexy"); a.Add(i); a.Add(g); for (int x = 0; x < a.Count; x++) Console.WriteLine(a[x]); } }

Alexy 10 abc

HashTable
The Hashtable provides a faster way of storage and retrieval of items of the object type. The Hashtable class provides support for key based searching. These keys are unique hash codes that are unique to a specific type. To remove an item from the Hashtable class, the Remove() method is used.

The statement hashTable.Remove(3) would remove the item Jini from the Hashtable object created in the code.

using System; using System.Collections; class Test { static void Main() { Hashtable hashTable = new Hashtable(); hashTable.Add(1, "Joydip"); hashTable.Add(2, "Manashi"); hashTable.Add(3, "Jini"); hashTable.Add(4, "Piku"); Console.WriteLine("The keysare:--"); foreach (int k in hashTable.Keys) { Console.WriteLine(k); }

Output:

The keysare:-4 3 2 1 Please enter the keyto search 2 Manashi

Console.WriteLine("Please enter the keyto search"); int p = int.Parse(Console.ReadLine()); Console.WriteLine(hashTable[p].ToString()); } }

Queue
The Queue is a data structure that provides a First-in-First-out collection of items of the System.Object type. The newly added items are stored at the end or the rear of the Queue and items are deleted from the front of the Queue.
using System; using System.Collections; class Test { static void Main() { Queue queueObject = new Queue(); queueObject.Enqueue("Joydip" ); queueObject.Enqueue("Steve"); queueObject.Enqueue("Jini"); while (queueObject.Count > 0) Console.WriteLine(queueObject .Dequeue()); } } Joydip Steve Jini

The Enqueue() method is responsible for storing items at the rear of the Queue and the method Dequeue() removes them one at a time from the front.

Stack
The Stack class is one that provides a Last-in-Firstout (LIFO) collection of items of the System.Object type. The last added item is always at the top of the Stack and is also the first one to be removed. The Push() method is responsible for storing items in the Stack The method Pop() removes them one at a time from the top of the Stack.
using System; using System.Collections; class Test { static void Main() { Stack stackObject = new Stack(); stackObject.Push("Joydip"); stackObject.Push("Steve"); stackObject.Push("Jini"); while (stackObject.Count > 0) Console.WriteLine(stackObject. Pop()); Jini } Steve } Joydip

Contents: Introduction Single-Dimensional Array Multi-Dimensional Array Jagged Array Array Class Properties

Arrays
Its Group of related data items that share a common name. In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array. You can declare an array of fixed length or dynamic. int [] intArray; Eg: Dynamic Array int [] intArray; Eg: fixed Array creates memory location for 5 intarray, intArray = new int[5]; beginning from 0,1,2,3,4 System.Array class is the name space, used as an abstract base type.

The variables in an array is called elements The value of each individual element in an array is accessed through its index value. Arrays in C# are zero-based; i.e. the first element in an array will always have an index of zero.

Arrays can be divided into four categories. These categories are 1. single-dimensional arrays, 2. multidimensional arrays or rectangular arrays, 3. jagged arrays, and 4. mixed arrays

Single Dimension Array


This is the simplest of all Arrays.Arrays are objects That means declaring an array doesnt create an array.After declaring an array, you need to instantiate an array by using new operator. Example: int[]name; //Declares an array in int name=new int[3]; //declares an array to store 3 //elements from index 0 to 2. name=new int[3]{29,6,99}; //declares and initializes array of 3 items

This same thing can be done with other data types.

Single Array
class simplearray { static void Main() { int[] intarray = new int[4]; intarray[0] = 1; intarray[1] = 2; intarray[2] = 3; intarray[3] = 4; foreach (int i in intarray) { OUTPUT:

1 2 3 4

Console.WriteLine(i.ToString()); } } }

Multi dimensional
These are array with more than one dimensional.It is declared as follows string[ , ] name; //2D Array string[ , , ]name; //3D Array After declaring we can initialize the array. int[,] num=new int[3,2]{{5,6},{2,7},{0,1}}; Here it can store 6 items of int and an examp le of fixed array string[,] name=new string[,]{ {alexy,dede},{roja,raja}}; here it stores 4 items of sting and an example of dynamic array.

Multi Array
class multiarray { static void Main() { string[,] namearray = new string[,] { {"Rosy","Amy"}, {"Peter","Albert"},{"Raja","Alexy"} }; for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) OUTPUT:

Element[0,0]=Rosy Element[0,1]=Amy Element[1,0]=Peter Element[1,1]=Albert Element[2,0]=Raja Element[2,1]=Alexy

Console.WriteLine("Element[{0},{1}] ={2}", i, j, namearray[i, j]); Console.Read(); }


}

Two Dimensional Array


class Twodimentional { public static void Main() { int[,] x; x = new int[4, 4]; x[0, 0] = 1; x[1, 1] = 1; x[2, 2] = 1; x[3, 3] =1; Console.WriteLine(x[0, 0] + Console.WriteLine(x[1, 0] + Console.WriteLine(x[2, 0] + Console.WriteLine(x[3, 0] + } }
OUTPUT:

1000 0100 0010 0001

" " " "

" " " "

+ + + +

x[0, x[1, x[2, x[3,

1] 1] 1] 1]

+ + + +

" " " "

" " " "

+ + + +

x[0, x[1, x[2, x[3,

2] 2] 2] 2]

+ + + +

" " " "

" " " "

+ + + +

x[0, x[1, x[2, x[3,

3]); 3]); 3]); 3]);

Jagged Arrays
Jagged Array is simply called array of arrays. In this elements of array are arrays. The elements of jagged array can be of different dimensions and sizes. Example: int[][] jarray=new int [3][];

The example declares an single-dimensional array that has three elements, each of which is a single-dimensional array of integers:
int[][] jarray=new int [3][];

These elements must be initialized before using in the program.

jarray[0]=new int[]{1,2,3,4,5};
jarray[1]=new int[]{22,66};

jarray[3]=new int[]{9,5,33,66,1,10,38,44};

We can access individual array elements like in the following way: int[][] jarray1= { new int[]{ 1,2,3,4,5}, new int[]{5,6,7,8}, new int[]{22,99} }; jarray1[0][1]=77; //assigning 77 to second element [1] of first array [0]; jarray1[2][1]=66; //assigning 66 to second element [1] of third array[2]; The following is a jagged array three elements of twodimensional int[][,] jaggedArray4 = new int[3][,] { new int[,] { {1,3}, {5,7} }, new int[,] { {0,2}, {4,6}, {8,10} }, new int[,] { {11,22}, {99,88}, {0,9} } };

Jagged Array
class Jagged { int[][] x = new int[2][]; void set() { x[0] = new int[2]; x[1] = new int[2]; x[0][0] = 1; //first array,first element x[0][1] = 2; //first array,second element } void show() { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { Console.WriteLine(x[i][j]); } } }

public static void Main() { Jagged j = new Jagged(); j.set(); j.show(); } }

OUTPUT:
1 2 0 0

ARRAY CLASS PROPERTIES.


IsFixedSize IsReadOnly Length : Return a value indicating if an Array has a fixed size or not. : Returns a value indicating if an Array is read- only or not. : Returns the total number of items in all hedimensions of an Array . Rank : Returns the number of dimensions of an Array. BinarySearch : This method searches a one-dimensional sorted Array for a value, using a binary search algorithm. Clear : This method removes all items of an Array and sets a range of items in the array to 0. Clone : This method creates a shallow copy of the Array. Copy : This method copies a section of one Array to another Array and performs type casting and boxing as required. CopyTo : This method copies all the elements of the current onedimensional Array to the specified one-dimensional Array starting at the specified destination CreateInstance : This method initializes a new instance of the Array class. GetEnumerator : This method returns an IEnumerator for the Array. GetLength : This method returns the number of items in an Array.

ARRAY CLASS PROPERTIES.


GetLowerBound : This method returns the lower bound of an Array. GetUpperBound : This method returns the upper bound of an Array. GetValue : This method returns the value of the specified item in an Array. IndexOf : This method returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of it. Initialize : This method initializes every item of the value-type Array by calling the default constructor of the value type. LastIndexOf : This method returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of it. Reverse : This method reverses the order of items in a onedimensional Array or in a portion of the Array. SetValue : This method sets the specified items in the current Array to the specified value. Sort : This method sorts the items in one-dimensional Array objects.

Using array properties


using System; Class Program { static void Main() { int[]num={99,24,56,3,15}; Array.Sort(num); foreach(int I in num) Console.WriteLine(I); Console.WriteLine(Length= +num.length); } }

Output
3 15 24 56 99 Length=5

Enumerator
a distinct type consisting of a set of named constants called the enumerator. Syntax: <modifier> enum <enum_name> Eg: enum Months { { // Enumeration list jan,feb,mar,apr } }

By default the first enumerator has the value of zero and the value of each successive enumerator is increased by 1. The following are the restrictions apply to an enum type in C# They can't define their own methods. They can't implement interfaces. They can't define properties or indexers. the use of enum makes the code more readable and selfdocumenting.

Simple Enum
using System; enum Months : long { jan = 10,feb = 20,mar } class MyClient { public static void Main() { long x = (long)Months.jan; long y = (long)Months.feb; long z = (long)Months.mar; Console.WriteLine("JANUAR Y={0},FEbriary = {1},March={2}",x,y,z); } } OUTPUT:

JANUARY=10, FEBUARY=20, MARCH=21

Contents:
Introduction Try and Catch Block Multiple Catch Block Finally Block User Exception

Exception Handling
To detect and handle run time errors. These exception can be due to user, logic or system errors. Three keywords are mainly used in this i.e. try, catch and finally. The try encloses the statements that might throw an exception whereas catch handles an exceptions if one exits. The finally can be used for doing any clean up process. Syntax: try { }

catch( type e) { }

finally { }

In try if there is no exception, it transfers to finally block. The Finally block is always executed. There is no usage of break, continue, return, goto. C# provides standard exception or user can create exception provided that it should inherit from System.Exception class. Run-time error: after successful compilation program may produce wrong results.
Compile time error: syntax errors will be detected and displayed by compiler.

Normal coding: class Notry { static void Main() { int e = 0; int div = 100 / e; Console.WriteLine(div); } }

Output: This code Will raise an Exception that DivideByZeroException is Unhandled. Now the code next to it contains TRY and CATCH block. Here in this controls passes from TRY block to CATCH block. Then it will execute this CATCH block and continues with the program.

Using try and catch


class Singletry { public static void Main() { int i = 0; int div=0; try { div = 100 / i; Console.WriteLine("This line is Exception"); } catch (DivideByZeroException e) {

Output:
This line is Exception Exception Occurred Result is 0

Console.WriteLine("Exception Occured"); } Console.WriteLine("Result is {0}", div); } }

Multiple Catch Block


class Multicatch { static void Main() { int[] a ={ 5, 10 }; int b = 5; try { int x = a[2] / b - a[1]; } catch (IndexOutOfRangeException e) { Console.WriteLine(e); } catch (ArgumentNullException o) { Console.WriteLine(o); } catch (ArrayTypeMismatchException n) { Console.WriteLine(n); } catch (DllNotFoundException k) { Console.WriteLine(k); } int y = a[1] / a[0]; Console.WriteLine(y=y); } }

OUTPUT:
System.IndexOutOfRangeException: Index was outside the bounds of the array. at ConsoleApplication1.ErrorHandling.Multi catch.Main() in C:\Documents and Se ttings\Administrator\Desktop\Alexy\Proj ects\ConsoleApplication1\ConsoleApplic ati on1\ErrorHandling\Multicatch.cs:line 15 Y=2

Array element 2 does not exist, hence index 2 is out of range, so the try block raises an exception and catching the right exception, leaving the rest alone.

Finally Block
class Finallyblock { static void Main() { int i = 0; int div = 0; try { div = 100 / i; Console.WriteLine("This line is Exception"); } catch (Exception e) { Console.WriteLine("INVALID"); } finally { Console.WriteLine("finally"); Console.WriteLine("Result is {0}", div); } } }
OUTPUT:

THIS IS INVALID DIVISION finally block Result is 0

First the try block will raise an exception, to the catch block. But note that the program is not terminated an it continues. How ever the finally block will be executed.

User Exception
class Myexception : Exception { public Myexception(string Messsage):base(Messsage) { Console.WriteLine("user defined exception"); } } class OwnException { public static void Main() { try { throw new Myexception(Raja"); } catch (Myexception e) { Console.WriteLine(e.Message); } Console.WriteLine("Last Statement"); } }

OUTPUT:

user defined exception Alexy Last Statement

Sealed Class
Sealed Classes is used to restrict the feature of inheritance. A class is declared as sealed simply by using the keyword sealed. In C# structs are implicitly sealed. Syntax: { .... } Sealed class SealedClass

Example
class Class1 { static void Main(string[] args) { SealClass Cls = new SealClass(); int total = Cls.Add(4, 5); Console.WriteLine("Total = " + total.ToString()); } } sealed class SealClass { public int Add(int x, int y) { return x + y; } }

OUTPUT:

Total=9

Sealing Methods
In C# a method can not be declared as sealed.

However when we override a method in a derived class, we can declare the overridden method as sealed.
By declaring it as sealed, we can avoid further overriding of this method. Sealed keyword serves the purpose of sealed. If a class is derived from a sealed class,compiler throws an error. We can mark a class or method as sealed for commercial reasons, in order to prevent a third party from extending our classes.

Contents:

Introduction Namespace and Instance Writing in a file Reading from a file

Files
With any programming language there is always a need to read and write to files. The class FileStream, which is actually derived from the Stream class, adds to Stream the functionality needed to read and write to files. Like other languages, C# utilizes a Stream class, which gives basic functionality when working with streams (any situation where you need to read and write data to some endpoint). The class FileStream, which is actually derived from the Stream class, adds to Stream the functionaly needed to read and write to files.

Namespace and Instance


System.IO provides all the necessary classes, methods, and properties for manipulating directories and files. create an instance of FileStream: FileStream file = new FileStream(C://path.txt", FileMode.option, FileAccess.option); FileMode specifies what the FileStream should do with the file to begin with. The options are: Append, Create, CreateNew, Open, OpenOrCreate, or Truncate, and can be accessed by FileMode.option. FileAccess specifies the file priveledges. The options are: Read, ReadWrite, or Write, and can be accesed by FileAccess.option. After reading or writing close the file file.Close();

Writing to a file
To write to a file we will need to use class StreamWriter, which is derived from the TextWriter class. StreamWriter sw = new StreamWriter(file); With StreamWriter, you have two options for writing to a file: Write, or WriteLine. sw.Write("Hello file system world!"); Now don't forget to close the stream when you are done! sw.Close();

using System; using System.IO; class Fileclass { static void Main() { FileStream file=new FileStream (C://Myfile.txt,FileMode.Crea te, FileAccess.Write); StreameWriter sw=new StreamWriter(file); sw.WriteLine(Hello); sw.WriteLine(Welcome); sw.WriteLine(Bye); sw.Close(); Console.Writeline(Success); file.Close(); } }

Output: Sucess In c drive a note pad will be created with the name Myfile.It will contain the following. Hello Welcome Bye

Reading from a file


To read from a file we will need to use class StreamReader. derived from the TextReader class. StreamReader sr = new StreamReader(file); With StreamReader, there are four options for reading from a file: Read, ReadBlock, ReadLine, or ReadToEnd. string s = sr.ReadToEnd(); ReadToEnd, which just like the title implies, reads the entire file. ReadLine, reads each and every line including spaces. sr.Close();

Using System; Using System.IO; Class Fileclass { static void Main() { FileStream file=new FileStream (C://Myfile.txt,FileMode.Open, FileAccess.Read); StreamReader sr=new StreamReader(file); string s=sr.ReadToEnd(); While(s!=null) { Console.WriteLine(s); s=sr.Readline(); } sr.close(); file.Close(); } }

Output:
Hello Welcome Bye

Contents:
Introduction Generic Terminology and Syntax Generic Type Generic Method Constraints Types of Constraints Generic Class

Generics

Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics are used to help make the code in the software components much more reusable. By the generic types in the System.Collections.Generic namespace-unless your type collection needs custom functionality, you won't even have to define a single collection type in your class library!

Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:(Cont)

public class GenericList<T> // Declare the generic class { //T=Type Parameter void Add(T input) { } } class TestGenericList { private class ExampleClass { } static void Main() { // Declare a list of type int GenericList<int> list1 = new GenericList<int>(); // Declare a list of type string GenericList<string> list2 = new GenericList<string>(); // Declare a list of type ExampleClass GenericList<ExampleClass> list3 = new GenericList<ExampleClass>(); } }

Generic Terminology and Syntax


Type Parameter : A type parameter is the core of enabling generic functionality. It is just like any other parameter in the sense that you pass an argument to it when you use the type or method. Generic Type and Generic Method: "generic type" and "generic method." A generic type is a type (class, struct, delegate, or event) that defines one or more type parameters, as in the MySample class in Example. A generic method is any method that defines one or more type parameters, as in the DoSomething method in Example. It is important to note that generic methods do not have to be declared within generic types Example: public class MySample<T> //generic type { public void DoSometing<K,V>() //generic method {} }

Normal Code
class Class1 { static void Main() { int[] intarrey ={ 1, 2, 3, 4, 5, 6 }; double[] doublearray ={ 1.2, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; char[] chararray ={ 'a', 'l', 'e', 'x', 'y' }; Console.WriteLine("This is Int Array"); Printarray(intarrey); Console.WriteLine("This is double array"); Printarray(doublearray); Console.WriteLine("This is char array"); Printarray(chararray); }
static void Printarray(int[] input) { foreach (int element in input) Console.Write(element+ " " ); Console.WriteLine("\n"); } static void Printarray(double[] input) { foreach (double element in input) Console.Write(element + " "); Console.WriteLine("\n"); } static void Printarray(char[] input) { foreach (char element in input) Console.Write(element + " "); Console.WriteLine("\n"); } }

OUTPUT

This is Int Array: 123456 This is Double Array: 1.2,2.2,3.3,4.4,5.5,6.6,7.7 This is char Array: alexy

This is lengthy process and also time consuming.

Generics Methods
class Class2 { static void Main() { int[] intarrey ={0,0,0,0,0,0,0 }; double[] doublearray ={ 1.2, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; char[] chararray ={ 'a', 'l', 'e', 'x', 'y' }; Console.WriteLine("This is Int Array"); Printarray(intarrey); Console.WriteLine("This is double array"); Printarray(doublearray); Console.WriteLine("This is char array"); Printarray(chararray); }

static void Printarray<E>(E[] input) { foreach (E element in input) Console.Write(element + " "); Console.WriteLine("\n"); } }

Output

This is Int Array: 123456


This is Double Array: 1.2,2.2,3.3,4.4,5.5,6.6,7.7 This is char Array: alexy By using generics the code is used for int,double and string.The length is reduced.But we get the same output.

Generic Type
public class Col<T> { T t; public T Val { get { return t; } set { t=value; } } }

public class ColMain { public static void Main() { //create a string version of our generic class Col<string> mystring = new Col<string>(); mystring.Val = "hello"; //set the value System.Console.WriteLine(mystring.Val); System.Console.WriteLine(mystring.V al.GetType()); //create another instance of our generic class, using a different type Col<int> myint = new Col<int>(); //load the value myint.Val = 5; //output the value System.Console.WriteLine(myint.Val); //output the value's type System.Console.WriteLine(myint.Val. GetType()); }

Generic Type
The class name col<T> indicates that this is of generic type.<T> is called the Type parameter. Variable declaration T t member variable with type of T. The actual value of T will be specified during construction of class(it will actually gets inserted by the CLR automatically). The actual value of T can be specified while creating the object as shown in the example.

Constraints
Constraints are a feature of .NET generics that enable the creator of a generic to specify that only certain types may be passed in as type arguments to his generic. Constraints solve a problem that involves the usage of type parameters within a generic type. Constraints are applied by using the contextual keyword where.

More than one constraints can be added using where Keyword.

Types of Constraints
Where T: struct The type argument must be a value type. Any value type except Nullable can be specified. Where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type. Where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last. Where T : <base class name> The type argument must be or derive from the specified base class. Where T : <interface name> The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic. Where T : U The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

class Factory<U> where U : new() { public static U GetNew() { return new U(); } } class Program { static void Main() { int i = Factory<int>.GetNew(); object obj = Factory<object>.GetNew(); Console.WriteLine(i); Console.WriteLine(obj); } }

OUTPUT:

0 object

// Here, 'i' is equal to 0 and 'obj' references an instance of the class 'object'.

Generic Class

Nongeneric Counterpart in System.Collections CollectionBase

Meaning in Life

Collection<T>

The basis for a generic collection

Comparer<T> Dictionary<K, V> List<T> Queue<T> Stack<T>

Comparer Hashtable ArrayList Queue Stack

Compares two generic objects for equality A generic collection of name/value pairs A dynamically resizable list of items A generic implementation of a first-in, first-out (FIFO) list A generic implementation of a last-in, first-out (LIFO) list A generic implementation of a sorted set of name/value pairs A generic implementation of a set of read-only items

SortedDictionary<K, V>

SortedList

ReadOnlyCollection<T>

ReadOnlyCollectionBase

Example
using System.Collections.Generic; public class MainClass { static void Main() { List<int> myInts = new List<int>(); myInts.Add(1); myInts.Add(2); myInts.Add(3); for (int i = 0; i<myInts.Count; i++) { Console.WriteLine("MyInts: {0}", myInts[i]); } }
using a generic List collection is similar to arrays. The Count property is a difference between collections and arrays in that an array uses a Length property for the same thing.

MyInts:1 MyInts:2 MyInts:3

The End

You might also like