• +91 9146141100
  • info@fosterbin.com
delegates-csharp
Delegates – C#
Posted on Categories C#Tags

Hi everyone,

Today we are going to add a new weapon to our arsenal called delegates, C# really provides interesting ways to do programming and delegates are a good example of it. So, let us study what delegates are and how they can make our programming experience more productive and make our code cleaner.

What is Delegate?

A delegate is a type that represents, reference to method with a particular return type and parameter list, and this reference can be changed dynamically. In other words, it is a pointer to function that matches signature with it
i.e. return type and parameter list.

When to use Delegates?

Sometimes, we need to programmatically change the method that is called or we need to pass functions as a parameter to another function, or we need to implement callback function, or we need to implement an event. In all cases, we can effectively make use of delegates.

How to create Delegate?

Syntax:
delegate <return type> <delegate-name> (<parameter list>);

Example:
delegate int <delegate-name>(int x, int y)

Use:
<delegate-name> sampleDelegate = new <delegate-name>(<method_name_having_two_int_parameters_and_returning_int_value>);

int retValue = sampleDelegate(10, 20);

Code Snippet:

delegates-code

 

More info
When we create an instance of a delegate we can associate it with one or more than one functions which match its signature, all of them will be called. The method we wish to attach to delegate need not be of the same class or struct it can be any method accessible over there, it may be an instance method or static also, as a result of this we can plug new functionality to existing classes also.

One comment
  1. Nice Information Provided on delegate,Which clear the concept very well.
    The Program is also nice for understanding.

Leave a Reply to Rushikesh Dattatray Raut Cancel reply

Your email address will not be published. Required fields are marked *

Recent Comments
Archives
Categories