You are on page 1of 13

C# Basics 2.6 Delegates and events 2.6.1 Delegates 2.6.1.1 Definition & declaration 2.6.1.2 Using delegate in C# 2.6.1.

3 Simple delegate example 2.6.2 Anonymous method 2.6.3 Events 2.6.3.1 Generating events

Definition;-A delegate is an object that can refer to a method. Therefore, when you create a delegate, you are creating an object that can hold a reference to a method. In other words, a delegate can invoke the method to which it refers. This is a one of the powerful features of C#. Same delegate can be used to call different methods during the runtime of a program by simply changing the method name. Thus, the method that will be called by a delegate is not determined at compile time, but at runtime. This is the principal advantage of a delegate. A delegate in C# is similar to a function pointer in C/C++ by which you can call any function by pointer. A delegate type is declared using the keyword delegate. Declaration: The general form of a delegate declaration is shown here:: Access-Modifier delegate ret-type name (parameter-list); Access-Modifier is Public , Private, Protected ,etc A delegate type is declared using the keyword delegate. ret-type is the type of value returned by the methods that the delegate will be calling. The name of the delegate is specified by name. The parameters required by the methods called through the delegate are specified in the parameter-list. Following step define how to write delegate in c#.Net. 1. Defining the delegate public delegate int DelCal (int value1, int value2);

2. Creating methods which will be assigned to delegate object //a method 1, that will be assigned to delegate objects having the EXACT Defination as delegate. public int add(int value1, int value2) { return value1 + value2; } //a method 2, that will be assigned to delegate objects having the EXACT Defination as delegate. public int sub( int value1, int value2)
{ } return value1 - value2;

3. Creating the delegate object and assigning methods to those delegate objects //creating the class which contains the methods that will be assigned to delegate objects MyClass mc = new MyClass(); //creating delegate objects and assigning appropriate methods having the EXACT signature of the delegate. Calculate obj1del = new DelCal (mc.add); Calculate obj2del = new DelCal (mc.sub); 4. Calling the methods via delegate objects //using the delegate objects to call the assigned methods Console.WriteLine("Adding two values: " + obj1del(10, 6)); Console.WriteLine("Subtracting two values: " + obj2del(10,4)); Let us take more simple example: using System; using System.Collections.Generic; using System.Text; namespace DelegateExample {

public delegate int DelCal (int value1, int value2); class DelegateDemo { public int add(int value1, int value2) //A Method which is called by Delegate. { return value1 + value2; } public int sub( int value1, int value2)
{ return value1 - value2; }

//A method 2, which is called by delegate.

} class Program { static void Main(string[] args) { MyClass mc = new MyClass(); //create object of Myclass.

DelCal obj1del = new DelCal (d.add); DelCal obj2del = new DelCal (d.sub); // Create object of Delegate and Pass a method which you want to call. Console.WriteLine("Adding two values: " + obj1del(10, 6)); Console.WriteLine("Subtracting two values: " + obj2del(10,4)); System.Console.ReadKey(); } } }

Output: Adding two values:16 Substracting two values:06

2.6.2 Anonymous method

Anonymous Methods
An anonymous method is one way to create an unnamed block of code that is associated with a specific delegate instance. An anonymous method is created by following the keyword delegate with a block of code. An anonymous Method is a method without name-which is why it is called anonymous. You dont declare anonymous method like regular method. Simple example. The following program uses an anonymous method that counts from 0 to 5. // Demonstrate an anonymous method. using System; // Declare a delegate type. delegate void CountIt(); class AnonMethDemo { static void Main() { // Here, the code for counting is passed // as an anonymous method. CountIt count = delegate { // This is the block of code passed to the delegate. for(int i=0; i <= 5; i++) Console.WriteLine(i); }; // notice the semicolon count(); } } This program first declares a delegate type called CountIt that has no parameters and returns void. Inside Main( ), a CountIt instance called count is created, and it is passed the block of code that follows the delegate keyword. This block of code is the anonymous method that will be executed when count is called. Notice that the block of code is followed by a semicolon, which terminates the declaration statement? The output from the program is shown here: 0

1 2 3 4 5 2.7 Inheritance The process of deriving a new class from already existing class is known as inheritance. Inheritance is one of the best concepts of object oriented programming language. One of the important characteristic of inheritance is reusability. Using inheritance you can define a general class that contains methods that likely to be common for other classes. Once such a general class is defined and tested you can derive new class from this general class and add its own methods. Thus there is no need to define same methods for all the class again and again. In this way inheritance allows you the facility of reusability. The class which is derived from general class inherits some or all features of the general class and add its own features to make it specific class. a class that is inherited is called a base class. The class that does the inheriting is called a derived class The general syntax for deriving a new class is given below:
class BaseClassName { } class DerivedClassName : BaseClassName { }

2.7.1 Types of inheritance C# supports two types of Inheritance mechanisms 1.Implementation Inheritance 2.Interface Inheritance What is Implementation Inheritance? When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance. What is Interface Inheritance? When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.

2.7.2 Implementation Inheritance When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance. Implementation Inheritance can be classified to 4 types.
Single Inheritance Hierarchical Inheritance Multi Level Inheritance Hybrid Inheritance

1. Single Inheritance
when a single derived class is created from a single base class then the inheritance is called as single inheritance.

public class A { } public class B:A { }

2. Hierarchical Inheritance
when more than one derived class are created from a single base class, then that inheritance is called as hierarchical inheritance.

public class A { } public class B:A { } public class C:A { }

3. Multi Level Inheritance


when a derived class is created from another derived class, then that inheritance is called as multi level inheritance.

public class A { } public class B:A { } public class C:B { }

4. Hybrid Inheritance
Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.

public class A { } public class B:A { } public class C:B { } public class D:B { }

Hinding Method: If a method with the same Signature(Same Name,return type & Argument),is declared in both Base and Derive Classes.then the Derived class Method hide the base class Method. For Example:
class BaseClass { public void DisplayMessage() { System.Console.WriteLine("I am From Base Class."); } }

class DerivedClass:BaseClass { //This is a Derived Class method which has same signature as Base Class. by using new keyword new public void DisplayMessage() { System.Console.WriteLine("I am from Derive Class."); } } class Program { static void Main(string[] args) { DerivedClass d = new DerivedClass(); //create object by calling Derived Class Constructor. BaseClass b = new DerivedClass(); d.DisplayMessage();//out put of Derived Class b.DisplayMessage();//output of Base Class System.Console.ReadKey(); } }

Output: I am from Derive Class. I am From Base Class.

As above code, BaseClass b = new DerivedClass(),Here we are creating object of a baseclass by calling constructor of Derived class. when we call a method through this object,It will call a method of Base class even if its created by Derived class Constructor.So we can say Base class method is hiding a Derived class Method. here,In derived class,we used a new keyword to prevent warning about method hiding generated by compiler. Now ,we will show how to prevent this hiding using Virtual and Override Keywords. Virtual Methods and Overriding When you want to allow a derived class to override a method of the base class, within the base class method must be created as virtual method and within the derived class method must be created using the keyword override. When a method declared as virtual in base class, then that method can be defined in base class and it is optional for the derived class to override that method. When it needs same definition as base class, then no need to override the method and if it needs different definition than provided by base class then it must override the method. Method overriding also provides more than one form for a method. Hence it is also an example for polymorphism. For Example:
class BaseClass { public virtual void DisplayMessage() { System.Console.WriteLine("I am From Base Class."); } }

class DerivedClass:BaseClass { //This is a Derived Class method which has same signature as Base Class. public override void DisplayMessage() { System.Console.WriteLine("I am from Derive Class."); } } class Program {

static void Main(string[] args) { DerivedClass d = new DerivedClass(); //create object by calling Derived Class Constructor. BaseClass b = new DerivedClass(); d.DisplayMessage();//out put of Derived Class b.DisplayMessage();//output of Derived Class System.Console.ReadKey(); } }

Output: I am from Derive Class. I am from Derive Class.

2.7.2.1 Calling base version of function In C# has special syntax for calling base class Method from derived class. Syntax base.Methodname(argument if?); Now see the below example how to call base method from derived class.
class BaseClass { public virtual void DisplayMessage() { System.Console.WriteLine("I am From Base Class."); } }

class DerivedClass:BaseClass { public override void DisplayMessage() { //Calling a Base Class method Using base Keyword base.DisplayMessage(); } }

class Program { static void Main(string[] args) { DerivedClass d = new DerivedClass(); d.DisplayMessage(); System.Console.ReadKey(); } }

2.7.2.1 Abstract class & function

There may be a situation where it is not possible to define a method in base class and every derived class must override that method. In this situation abstract methods are used. When a method is declared as abstract in the base class then it is not possible to define it in the base class and every derived class of that class must provide its own definition for that method. When a class contains at least one abstract method, then the class must be declared as abstract class. It is mandatory to override abstract method in the derived class. When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method. Example

The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as abstract in Shape class and as Shape class contains abstract methods it is declared as abstract class.

using System; namespace AbstractDemo { //Abstract class abstract class Shape { public float R, L, B;

//Abstract methods can have only declarations public abstract float Area(); } class Circle : Shape { public Circle() { Console.Write("Enter Radius : "); R = float.Parse(Console.ReadLine());

public override float Area() { return 3.14F * R * R; } } class MainClass { static void Main() { Circle C = new Circle(); System.Console.WriteLine("Area of Circle is;" + C.Area()); Console.Read(); } }

Output
Enter Radius : 5 Area : 78.5

Note
In the above example method calculate takes a parameter of type Shape1 from which rectangle1 and circle1 classes are inherited. A base class type parameter can take derived class object as an argument. Hence the calculate method can take either rectangle1 or circle1 object as argument and the actual argument in the parameter S will be determined only at runtime and hence this example is an example for runtime polymorphism.

2.7.2.1 Sealed class & method 2.7.2.1 Constructors of derived class 2.7.3 Modifiers 2.7.3.1 Visibility modifiers 2.7.3.2 Other modifiers 2.7.4 Overview of Abstraction 2.7.5 Interfaces 2.7.5.1 Definition & declaration 2.7.5.2 Derived interface

You might also like