Monday, September 10, 2012

Delegates in C#

In simple words delegate is a type that references to a method with a particular parameter list and a return type. You can invoke(call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are methods invoked through delegates. Delegate is a similar concept as function pointers in C and C++.

The ability to pass methods as parameters makes delegates ideal for defining callbacks. (When to use delegates, link2). Delegates are ideal to encapsulate codes. For example when you attach an event handler to a button, the handler becomes a delegate. The button doesn't need to know what it does. (Difference between Delegate and an Event).

Delegate types are derived from Delegate class. Delegate types are sealed and cannot be derived from. The ability to pass delegate as a parameter to a method and to call the delegate at a later time is known as asynchronous callback. 

When to use Delegates and Interfaces
Interfaces and delegates allows developer to separate type declaration and implementation. Use the following guidelines to decide.

Use delegates when,
  • Event based design pattern is used
  • Easy composition is desired
Use interfaces when,
  • There are group of related methods that might be called
  • Class only needs one implementation of the method
Source : MSDN, StackExchange

Delegates with Named Methods




Delegate with Anonymous Method

C# 2.0 introduced anonymous methods. Anonymous methods enables you to omit parameter list. This means anonymous method can be converted to delegates with variety of signatures. (This is not possible with Lambda expressions). Anonymous methods provide a way to pass a code block as a delegate parameter. They are basically methods without a name.


Lambda Expressions

Lambda expression is a anonymous function that you can use to create delegates or expression tree types. These are useful for writing LINQ query expressions. 

To create lambda expressions you specify any input parameters on the left side of => lambda operator and the expression or statement block on the other side. You can assign this expression to a delegate type. 



There are different types of lambda expressions,
  • Expression lambdas
  • Statement lambdas
  • Async lambdas
Lambda Expressions (MSDN)

Resources

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook