Thursday, 14 July 2011

Delegates in C#

A delegate is a type that safely wraps/encapsulate a method. It is similar to 'function pointers' in C/C++, but it's type safe.

When to use a delegate

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.

There was a good example given on a book that I recently referenced.'Consider your will—your last will and testament. It’s a set of instructions—“pay the bills, make a donation to charity, leave the rest of my estate to the cat,” for instance. You write it before your death, and leave it in an appropriately safe place. After your death, your attorney will (you hope!) act on those instructions.'

In order to a delegate to proceed, following four things need to happen:* The delegate type needs to be declared.* There must be a method containing the code to execute.* A delegate instance must be created.* The delegate instance must be invoked.

Declaring delegate typeDeclaration of a delegate type specifies what kind of action can be represented by instances of the type.

E.g :

delegatevoid MySampleDelegate(string zParameter)

If we are creating an instance of the above delegate, we should have a method with one string parameter and void return type.

Method containing the code to executeThere should be a method which matches the signature of the delegate. Method can be either static or non static. I will take two examples to illustrate a static method and a non static method. I will use the following two methods in the 'DelegateClass' class.

Instead of using separate delegate instances, you can combine and execute delegates. We have to use the 'Combine' method in Delegate class. To illustrate this I will alter my 'DelegateClass' as shown below :

About Me

My passion lies in building business intelligence and data-based solutions, writing about things I work with and talking about it. New technologies relevant to my line of work interest me and I am often seen playing with early releases of such technologies.
My current role involves architecting and building a variety of data solutions, providing database maintenance and administration support, building the organization’s data practice, and training and mentoring peers.
My aspiration over the next several years is to achieve higher competency and recognition in the field of Data Analytics and move into a career of data science.
Specialities: SQL Server, T-SQL Development, SQL Server Administration, SSRS, SSIS, C#, ASP.Net, Crystal Reports