Showing posts with label delegate. Show all posts
Showing posts with label delegate. Show all posts

Wednesday, September 18, 2013

create Custom Event in C#

using System;

public delegate void CarOwnerChanged(string o);
public class car
{

       public event CarOwnerChanged OwnerChanged;
       private string owner;

         public string car_owner
          {

           get
              {
                return owner;
              }

           set
              {
                 owner = value;
                  if (OwnerChanged != null)
                     {
                        OwnerChanged(owner);
                      }
                }

            }

}
class office
{

     public static void Main()
     {

         car Viru= new car();
          
Viru.OwnerChanged+=new CarOwnerChanged(parking_call);
          
Viru.car_owner = "Viru Maurya";
      }

      public static void parking_call(string ow)
       {
          Console.WriteLine(ow);
       }
}

Tuesday, June 25, 2013

What is delegate

q-1. What is delegate.
A delegate is a class whose object (delegate object) 
can store a set of references to methods. This delegate
object is used to invoke the methods


The Delegate class is the base class for delegate types. However, only the 

system and compilers can derive explicitly from the Delegate class or from the 

MulticastDelegate class. It is also not permissible to derive a new type from a

 delegate type. The Delegate class is not considered a delegate type; it is a 

class used to derive delegate types

q-2. How delegate Works internally .

whenever we declare delegate in c# initially it is
behaving as a keyword but when program gets compiled
the keyword called delegate converted into class and
compiler makes sealed class for delegate.

The sealed class implicitly inherited from multicast
delegate and multicastDelegate class implicitly inherited
from Delegate class.

multicastDelegate class and Delegate class both are marked
as a Abstract.

q-3. Why multicastDelegate class is needed?

A delegate is a class whose object (delegate object)
can store a set of references to methods means the
object of delegate class can hold the multiple method
references due to multicastDelegate.

q-4. Why Delegate class is needed?
The Delegate class plays a major role in case of
Asynchronous call back patteren.

Delegate class is carrying some major functions
like BeginInvoke() and EndInvoke() .

suppose we create a class for GUI Level like Windows Form,Web Form.
In this case we can't call a function of that class without Event.

Event can't created without delegate.There are several inbuilt
delegate class are(EventHandler,PageHandler,WebServiceHandler).

eg
using System;
using System.Windows.Forms;

class MyWin:Form
{

Button b1;

public MyWin()
{
b1=new Button();
b1.Text="Save";
this.Controls.Add(b1);

b1.Click+=new EventHandler(save);
}

protected void save(Object o,EventArgs e1)
{
MessageBox.Show("Ready to save the record in a table");
}
public static void Main()
{
MyWin m=new MyWin();
m.ShowDialog();
}
}

// In the above program,class MyWin inherited from
Form class and Button is added to the Form.
It shows if user wants to perform any action on
the he has to click on a Button.Means without
Click he can't perform any action.

Button class is provided the Event and for Event
delegate is needed.

Friday, April 5, 2013

Difference between Delegate and Interface


1.Delegates can only be methods. Here is an example:
delegate void sampleDelegate();

Interface can include both properties and methods.
Here is an example for an interface:

interface ItestInterface
{
int paraml {
get; set; }
void sampleMethod();
}

2. Delegate can be applied to only one method at a time When a class implements an interface, it can implement all the methods associated with it

3. You can use a delegate that is visible in your scope
You can use an interface only when your class or struct implements it

4. Within a class, you can implement the same delegate any number of times. Assume that either sampleClass1 or sampleClass2 of Examplel includes a method called sampleMethod2( ) with the same signature as that of delegate, then the same delegate can be used to access both sampleMethod() as well as sampleMethod2( )
Within a class, you can implement an interface method only once. In Example2, interface ITestInterface has a method called sampleMethod(). When sampleClass1 implements ITestInterface it implements sampleMethod() only once. If not, then it will end up in error.

5. Delegate can implement any method that shares the same signature as that of the delegate When an interface method is implemented, same method name and signature has to be overridden.

6. Delegate is mainly used for handling events
Interfaces are not used for handling events

7. You need not bother about the other methods available in the class.You are concerned about only the method that matches delegate signature.
When a class implements an interface, though the class requires only one method it has to implement all the methods of the interface

8. To access a method using delegate, you need not require any access to the instance of the class where the method is defined
To access the method, you need an instance of the class which implements the interface or you need an interface reference pointing to the method implemented by the class

9.You can access anonymous methods using delegates
You cannot access anonymous methods.Only named methods declared in interface can be accessed by the implementing class.

10.When you call a method using a delegate, all the method pointers associated with the delegate will be scanned through before the method execution. This is not a direct method call as you assume. It has a considerable performance overhead.
When you are calling a method using interface reference, you are directly accessing the method of the class that implements the interface. This is a direct method call and it doesn't have any overhead.

11. Delegates can wrap methods of sealed classes.Sealed classes are those which cannot be inherited.Accessing sealed types is not permissible in interface.

12. Delegates can wrap any method matching its signature irrespective of which ever class the method belongs to.
Class can implement any number of interfaces and it should override only the methods belonging to those interfaces

13. Delegates can wrap static methods. Examplel discussed above has used the delegate to wrap a static method called sampleMethod()
This provision is not available with interfaces .

14. Delegate cannot involve in inheritance.
Interface can inherit other interfaces. When a class implements that interface, it has to implement all the methods belonging to the interface and its inherited interfaces as well.
Here is an example of an interface inheriting from other interfaces:
interface IInterface: IInterface,1 IInterface2
{
void sampleMethod1();
void sampleMethod2();
}

Friday, November 16, 2012

Understanding Delegates

A delegate is an important element of C# and is extensively used in every type of .NET application. A delegate is a class whose object (delegate object) can store a set of references to methods. This delegate object is used to invoke the methods. Many developers find delegates complicated. But believe me, it’s a simple concept to understand. In this article we will see how delegates work and in what situations they are used.
Let’s start with a simple program that shows how to declare and use a delegate.


class sample
{
  delegate void del1();
  delegate void del2 (int i);
  public void fun()
  {
   del1 d1 = new del1 (f1);
   d1();
   del2 d2 = new del2 (f2) ;
   d2 ( 5 ) ;
  }
  public void f1()
  {
   Console.WriteLine (“Reached in f1”) ;
  }
  public void f2 (int i)
  {
   Console.WriteLine (“Reached in f2”) ;
  }
}
In the sample class we have declared two delegates—del1 and del2. The statement delegate void del1( ) ;
indicates that the delegate del1 is going to encapsulate methods, which takes no parameter and returns void. When this statement is encountered, a class del1 derived from a pre-defined class MultiCastDelegate gets created. Similarly, the statement delegate void del2 ( int i ) ; indicates that the delegate del2 will be used for methods taking one integer and returning a void. This statement would create another class del2 derived from the MultiCastDelegate class. The classes del1 and del2 are called ‘delegate classes’. To use the delegate class, like any other class, we have to declare its reference. We have declared the reference to delegate class del1 in the fun( ) method through the statement del1 d1 = new del1 ( f1 ) ;
This would create a delegate object d1. To the constructor of the delegate class we have passed the address of the method f1( ). C++ programmers may know that mentioning a method name without parentheses represents its address. The delegate object would now hold an address of the method f1( ). Next, we have called the f1( ) method using the delegate object d1. This is achieved using the statement d1( ) ;
If d1 is an object, how can we use it as if it is a method? Actually, the call d1( ) gets converted into a call to the d1.Invoke( ) method. The Invoke( ) method calls the f1( ) method using its address stored in delegate object. A delegate can contain references to multiple methods. In this case a single call to Invoke( ) calls all the methods.
Similar to d1 we have instantiated another delegate object d2 and stored in it an address of the method f2( ). As the method f2( ) takes an integer as a parameter we pave passed 5 to d2( ). The value 5 would get passed to all the methods whose references are stored in this delegate object. This makes it obvious that the signature of the delegate and that of the methods to be invoked using the delegate must be identical.
If we create an object of sample class and call the fun( ) method both the f1( ) and f2( ) methods would get called through d1 and d2 respectively.
Delegates make possible calling of methods using reference to methods the object oriented way. This avoids using any complex technique like pointers to functions.
Delegates in Inheritance
Suppose there is a base class and a class derived from this class. A method is invoked from a base class method using a delegate. We can initialise this delegate in derived class so that when the method is invoked from the base class it is the derived class’s method that would get called. Here is the program that works similar to this situation.
using System;

namespace delegateinherit
{
  public delegate void del1();
  class mybase
  {
   public del1 d;
   public void fun()
   {
    d();
   }
  }
  class der : mybase
  {
   public der()
   {
    d = new del1 (f1);
    fun();
    d = new del1 (f2);
    fun();
   }
   public void f1()
   {
    Console.WriteLine (“Reached in f1”) ;
   }
   public void f2()
   {
    Console.WriteLine (“Reached in f2”) ;
   }
  }
  class Class1
  {
   static void Main (string[] args)
   {
    der d = new der();
   }
  }
}
Here, from the fun( ) method of the mybase class we have used the delegate object d to invoke a method. The fun( ) method is called twice from the constructor of the derived class der. Before calling fun( ) method, we have associated the delegate d, first with method f1( ) and then with f2( ). Thus, if we create an object of the der class, first the f1( ) and then f2( ) method get called. We can invoke both the methods in a single call to fun( ) as shown below.
d = new del1 ( f1 ) ;
d += new del1 ( f2 ) ;
fun( ) ;
Where Delegates are useful
In a general WinForm application, a class Form1 gets created, which is derived from the Form class. If we want to handle mouse click messages, we override the OnMouseDown( ) message handler in the Form1 class. When we click the mouse button, control reaches to the OnMouseDown( ) of the derived class i.e Form1 class because of the simple rule of inheritance. But if we click on a push button on the form, the OnMouseDown( ) of the Form1 class does not get called. Because Form1 class is not derived from the class that creates button. In such a situation, delegates prove useful. Calling methods using delegate require only that the signature of methods and that of the delegate should match. It does not require any inheritance chain to call the appropriate method. So, in .NET, all the event handlers are called through delegates, instead of relying on the inheritance chain.
Delegate at work
As said earlier, all the event handlers are called using delegates. We will now see a dummy program to explain how the Paint event handler must be getting called using a delegate.
using System;
namespace delegateatwork
{
   public delegate void PaintHandler();
   class Form
   {
  public PaintHandler Paint ;
  public void OnPaint()
  {
   Paint();
  }
   }
   class form1 : Form
   {
  public form1()
  {
   Paint += new PaintHandler (form1_Paint);
   OnPaint() ;
  }
  public void form1_Paint()
  {
   Console.WriteLine (“form1_Paint”);
  }
 }
   class Class1
   {
  static void Main (string[] args)
  {
   form1 f = new form1();
  }
   }
}
We have designed a class Form1 that contains a method called Form1_Paint( ). The Form1 class is derived from the Form class. In the Form class we have declared an object Paint of the delegate class PaintHandler. In Main( ) we have instantiated an object of the Form1 class. This results in its constructor being called. In the constructor of the Form1 class we have initialised the Paint object and encapsulated in it the Form1_Paint( ) method. Next we have called the OnPaint( ) method of the Form class (in WinForm application Paint event gets generated automatically), which in turn calls the Form1_Paint( ) method via Paint.