Tuesday, November 22, 2011

Delegates and Events


What is a delegate?
Delegate is a reference type that safely encapsulates a method. Once the delegate is instantiated a method call made to the delegate would be passed to method by delegate.

How do you declare a delegate?
public delegate void SaveDelegate(Dataset Ds)

Which class are delegate type derived from?
They are derived from Delegate class.

Reason for Delegates existence or major Use of Delegate?
Delegates is a type or an object. Thus when you instantiate a delegate with method like
SaveDelegate delObj=new SaveDelegate(SomeMethod) or SaveDelegate delObj==SomeMethod
We can pass the delObj as object to other functions or use it as return type. Thus can further call the methods from the calling functions. This is also known for asynchronous callback

Difference between delegates for static method and instance method?
When wrapping instance method it references both instance and method. When used for static method it references only method.

What is multicasting in delegates?
Delegates can call more than one method when invoked, this is called as multicasting.
SaveDelegate d1=obj.SomeMethodA();
SaveDelegate d2=obj.SomeMethodB();

SaveDelegate allMethods=d1+d2

What are anonymous methods?
Methods by using which we can reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.

e.g
// Declare a delegate
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instatiate the delegate type using an anonymous method:
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call:
        p("The delegate using the anonymous method is called.");
    }
}

Guidelines of when to use delegate instead of Interface from MSDN/
Use a delegate when:
·         An eventing design pattern is used.
·         It is desirable to encapsulate a static method.
·         The caller has no need access other properties, methods, or interfaces on the object implementing the method.
·         Easy composition is desired.
·         A class may need more than one implementation of the method.

Use an interface when:
·         There are a group of related methods that may be called.
·         A class only needs one implementation of the method.
·         The class using the interface will want to cast that interface to other interface or class types.
·         The method being implemented is linked to the type or identity of the class: for example, comparison methods.

1 comment:

navya said...

I learnt the importance of delegates and events to use multiple methods simultaneously in my C# Training and I want to know how to call the methods with return type in delegate and how to hold the return value from each method.