top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are Delegates and Events in C#/.NET?

0 votes
307 views
What are Delegates and Events in C#/.NET?
posted Sep 28, 2015 by Sathaybama

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The delegate topic seems to be confusing and tough for most developers. This article explains the basics of delegates and event handling in C# in a simple manner.

A delegate is one of the base types in .NET. Delegate is a class to create delegates at runtime.

A delegate in C# is similar to a function pointer in C or C++. It's a new type of object in C#. A delegate is a very special type of object since earlier the entire the object was used to defined contained data but a delegate just contains the details of a method.

The need for delegates

There might be a situation in which you want to pass methods around to other methods. For this purpose we create delegates.

A delegate is a class that encapsulates a method signature. Although it can be used in any context, it often serves as the basis for the event-handling model in C# but can be used in a context removed from event handling (for example passing a method to a method through a delegate parameter).

One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.

Example

public delegate int DelegateMethod(int x, int y);

Any method that matches the delegate's signature, that 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.

Delegate magic

In a class we create its object, that is an instance, but in a delegate when we create an instance it is also referred to as a delegate (in other words whatever you do, you will get a delegate).

A delegate does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

Benefit of delegates

In simple words delegates are object oriented and type-safe and very secure since they ensure that the signature of the method being called is correct. Delegates help in code optimization.

Types of delegates

Singlecast delegates
Multiplecast delegates

A delegate is a class. Any delegate is inherited from the base delegate class of the .NET class library when it is declared. This can be from either of the two classes System.Delegate or System.MulticastDelegate.

Singlecast delegate

a Singlecast delegate points to a single method at a time. In this the delegate is assigned to a single method at a time. They are derived from the System.Delegate class.

Multicast Delegate

When a delegate is wrapped with more than one method then that is known as a multicast delegate.

In C#, delegates are multicast, which means that they can point to more than one function at a time. They are derived from the System.MulticastDelegate class.

There are three steps in defining and using delegates:

  1. Declaration

To create a delegate, you use the delegate keyword.

[attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);

The attributes factor can be a normal C# attribute.

The modifier can be one, or an appropriate combination, of the following keywords: new, public, private, protected, or internal.

The ReturnType can be any of the data types we have used so far. It can also be a type void or the name of a class.

"Name" must be a valid C# name.

Because a delegate is some type of a template for a method, you must use parentheses, required for every method. If this method will not take any arguments then leave the parentheses empty.

Example

public delegate void DelegateExample();

The code piece defines a delegate DelegateExample() that has a void return type and accepts no parameters.

  1. Instantiation

DelegateExample d1 = new DelegateExample(Display);

The preceding code piece shows how the delegate is initiated.

  1. Invocation

d1();

The preceding code piece invokes the delegate d1().

The following is a sample to demonstrate a Singlecast delegate:

using System;

namespace ConsoleApplication5

{

class Program

{

    public delegate void delmethod();



    public class P

    {

        public static void display()

        {

            Console.WriteLine("Hello!");

        }



        public static void show()

        {

            Console.WriteLine("Hi!");

        }



        public void print()

        {

            Console.WriteLine("Print");

        }

    }

    static void Main(string[] args)

    {

        // here we have assigned static method show() of class P to delegate delmethod()

        delmethod del1 = P.show;



        // here we have assigned static method display() of class P to delegate delmethod() using new operator

        // you can use both ways to assign the delagate

        delmethod del2 = new delmethod(P.display);



        P obj = new P();



        // here first we have create instance of class P and assigned the method print() to the delegate i.e. delegate with class

        delmethod del3 = obj.print;



        del1();

        del2();

        del3();

        Console.ReadLine();

    }

}

}

The following is a sample to demonstrate a Multicast delegate:

using System;

namespace delegate_Example4

{

class Program

{

    public delegate void delmethod(int x, int y);



    public class TestMultipleDelegate

    {

        public void plus_Method1(int x, int y)

        {

            Console.Write("You are in plus_Method");

            Console.WriteLine(x + y);

        }



        public void subtract_Method2(int x, int y)

        {

            Console.Write("You are in subtract_Method");

            Console.WriteLine(x - y);

        }

    }

    static void Main(string[] args)

    {

        TestMultipleDelegate obj = new TestMultipleDelegate();

        delmethod del = new delmethod(obj.plus_Method1);

        // Here we have multicast

        del += new delmethod(obj.subtract_Method2);

        // plus_Method1 and subtract_Method2 are called

        del(50, 10);



        Console.WriteLine();

        //Here again we have multicast

        del -= new delmethod(obj.plus_Method1);

        //Only subtract_Method2 is called

        del(20, 10);

        Console.ReadLine();

    }

}

}

The following are points to remember about delegates:

Delegates are similar to C++ function pointers, but are type safe.
Delegate gives a name to a method signature.
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.
C# version 2.0 introduces the concept of Anonymous Methods, that permit code blocks to be passed as parameters in place of a separately defined method.
Delegates helps in code optimization.

Usage areas of delegates

The most common example of using delegates is in events.
They are extensively used in threading.
Delegates are also used for generic class libraries, that have generic functionality, defined.

An Anonymous Delegate

You can create a delegate, but there is no need to declare the method associated with it. You do not need to explicitly define a method prior to using the delegate. Such a method is referred to as anonymous.

In other words, if a delegate itself contains its method definition then it is known as an anonymous method.

The following is a sample to show an anonymous delegate:

using System;

public delegate void Test();

public class Program

{

static int Main()

{

...

answer Sep 28, 2015 by Shivaranjini
...