latest Post

Delegates in C#

 Delegates in C#

Delegate is one of the base types in .NET. Delegate is a class, which is used to create delegate at runtime.

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

Need of delegate

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

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 (e.g. 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, which 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 class we create its object, which is instance, but in delegate when we create instance that is also referred to as delegate (means whatever you do you will get delegate).

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 as they ensure that the signature of the method being called is correct. Delegate helps in code optimization.

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

Singlecast delegate

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

Multicast Delegate

When a delegate is wrapped with more than one method 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 System.MulticastDelegate class.

About Mallikarjun A

Mallikarjun A
Recommended Posts × +

0 comments:

Post a Comment