Delegates in c#

Posted by Techie Cocktail | 12:32 AM | | 1 comments »

A delegate is the communication channel between the event source (an object that raises the event) & the event receiver (the object responding to the event) and is called as the Event Handler.

A delegate is a reference type that encapsulates a method with a specific signature and return type. Any matching method can be encapsulated. Delegates are similar to function pointers but are object-oriented and type safe. They allow methods to be passed as the parameters

There are three steps in defining and using delegates:

1. Declaration:
A delegate is created using the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it.

2. Instantiation:
To use the delegate, you need to instantiate it, to specify the method that needs to be called.

3. Invocation:
A delegate object is used to invoke a method similar to how a method call is made.

Example:

using System;

namespace SampleDelegate
{
// Declaration
public delegate int MyDelegate(int a, int b);

class MyDelegateClass
{
public static int Add(int number1, int number2)
{
return number1 + number2;
}

public static void Main()
{
// Instantiation
MyDelegate _myDelegate = new MyDelegate(Add);

// Invocation
int result = _myDelegate(5, 5);
}
}
}

1 comments

  1. Leslie Lim // August 4, 2016 at 8:31 PM  

    You have some really good ideas in this article. I am glad I read this. I agree with much of what you state in this article. Your information is thought-provoking, interesting and well-written. Thank you.

    www.imarksweb.org