CODE DIGEST
Skip Navigation LinksHome » Article » Csharp Article » Delegates and Anonymous methods in C#   You are not logged in.
Search
 

Technologies
 

CodeDigest Navigation
 

Technology News
Read more..

Read more..

Read more..

 

Community News
Read more..

Read more..

 
Delegates and Anonymous methods in C#
By Satheesh babu
Posted On Feb 18, 2008
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 1
Category:
Print this article.

Delegates and Anonymous methods in C#

 

Introduction

C# 2.0 introduced many new features that increased the powerfulness of the language. Anonymous method is one such feature given by C# 2.0. This article will explore the anonymous methods and its basics. I assume that reader knows the basics of C# language to understand this article.

 

What is an Anonymous method?

An anonymous method is a method without any name. To understand better, a normal method is one which will have a name, return type optionally arguments and an access modifier. So, an anonymous method in C# 2.0 is a feature to have methods without name.

 

Where should I use an Anonymous method?

Anonymous methods can be used in the place where there is a use of a delegate. To understand anonymous methods we should understand the usage of delegate first. The following section of this article gives you an idea about delegate.

Understanding Delegate:

Delegate is similar to function pointer in C and C++. A function pointer in C is a variable that points to function. Similarly, a delegate is a reference type in .net that is used to call the methods of similar signature as of the delegate. For example, consider a C# method,

 

void PrintName(string Name)

{

Response.Write("Name is "+Name+"<br>");

}

 

To call the above method using delegate we should declare a delegate with similar signature,

 

delegate void DelegateTest(string n);

 

Before calling we should initialize or register the delegate with the method like,

 

DelegateTest del = new DelegateTest(this.PrintName);

 

Finally we can call the function by,

 

Del(“Satheesh Babu”);

 

So what makes the real difference between C language function pointer and a delegate is, at a given time a function pointer can point to a single function only i.e. it can be used to call a single function only. But delegate are by default they are multicast delegate, means they can be used to call multiple functions at a time. Consider a function,

void PrintAddress(string Address)

{

Response.Write("City he lives is "+Address);

}

 

The below code will explain how to call PrintName and PrintAddress methods using a delegate,

 

DelegateTest del = new DelegateTest(this.PrintName);

del += new DelegateTest(this.PrintAddress);

del(“Chidambaram”);

 

So the output will be,

Name is Chidambaram

City he lives is Chidambaram

 

It normally does it use of the += operator. So += operator is used to register a function and -= will remove the registration from the delegate. Consider,

 

DelegateTest del = new DelegateTest(this.PrintName);

del += new DelegateTest(this.PrintAddress);

del -= new DelegateTest(this.PrintAddress);

 

The output of above code will be,

 

Name is Chidambaram

 

The other difference between a delegate and a function pointer is, a delegate is type safe, means it will throw a compilation error if a method with different signature is assigned to the delegate.

 

Other than the above examples the delegates are used in event handling, for callbacks etc. For example, if you see the Web form designer code in Visual studio 2003 there will be,

 

btnCheck.Click += new EventHandler(this.btnCheck_Click);

 

Here EventHandler is a delegate that is registered with btnCheck_Click event.

 

Back to Anonymous methods:

 

The syntax of an anonymous method consists of the keyword delegate, an optional parameter list and method body enclosed in parenthesis.

 

delegate(Optional parameters)

{

Body of the method.

};

 

So looking at the answer of the question “Where should I use an Anonymous method?” the anonymous representation to implement the PrintName method will be,

 

delegate void DelegateTest(string n);

protected void Page_Load(object sender, EventArgs e)

{

DelegateTest Anodel = delegate(string Name)

{

Response.Write("Name is " + Name + "<br>");

};

}

 

Calling is again by,

Anodel(“Satheesh Babu”);

 

The output will be,

Name is Satheesh Babu

 

Similar to delegate, To call multiple methods we can use += operator,

 

delegate void DelegateTest(string n);

protected void Page_Load(object sender, EventArgs e)

{

DelegateTest Anodel = delegate(string Name)

{

Response.Write("Name is " + Name + "<br>");

};

Anodel += delegate(string Address)

{

Response.Write("City he lives is " + Address);

};

Anodel("Chidambaram");

}

 

The output will be,

Name is Chidambaram

City he lives is Chidambaram

 

An argumentless anonymous method will be like,

 

delegate void DelegateTestWithoutParam();

protected void Page_Load(object sender, EventArgs e)

{

 

//Parameterless anonymous methods

DelegateTestWithoutParam delparam = delegate()

{

Response.Write("<hr><b>Parameterless anonymous method</b><br><hr>");

Response.Write("Name is Satheesh Babu");

};

delparam();

}

 

The output will be,

Name is Satheesh Babu

 

Use of Anonymous methods in Event handling:

 

Like wise we can use anonymous methods for events like button click, dropdownlist selected item change, etc. Consider,

btnCheck.Click += new EventHandler(this.btnCheck_Click);

 

Here “btnCheck.Click” is expecting a delegate and hence we can use anonymous methods. So the event can be written as,

 

protected void Page_Load(object sender, EventArgs e)

{

//Event Handling using anonymous Methods

btnCheck.Click += delegate(object s, EventArgs ee)

{

Response.Write("<hr><b>Event Handling using Anonymous Methods</b><br><hr>");

Response.Write("Name is Satheesh Babu<br><hr>");

};

}

 

The out put will be,

Event Handling using Anonymous Methods

Name is Satheesh Babu

 

Note:

1) If a variable is declared outside the anonymous method it can be accessed inside the anonymous method, i.e. the below code is valid.

 

delegate void DelegateTestWithoutParam();

protected void Page_Load(object sender, EventArgs e)

{

string name = “Satheesh Babu”;

//Parameterless anonymous methods

DelegateTestWithoutParam delparam = delegate()

{

Response.Write("<hr><b>Parameterless anonymous method</b><br><hr>");

Response.Write("Name is "+ name);

};

delparam();

}

 

The below code which is trying to access a variable declared inside anonymous method is invalid and will throw a compilation error.

 

delegate void DelegateTestWithoutParam();

protected void Page_Load(object sender, EventArgs e)

{

//Parameterless anonymous methods

DelegateTestWithoutParam delparam = delegate()

{

string name = “Satheesh Babu”;

Response.Write("<hr><b>Parameterless anonymous method</b><br><hr>");

};

Response.Write("Name is "+ name);

delparam();

}

 

2) When an anonymous method is declared without parenthesis, it can be assigned to a delegate with any signature.

 

delegate void DelegateTest(string n);

protected void Page_Load(object sender, EventArgs e)

{

DelegateTest DiffAnodel = delegate

{

Response.Write("<hr><b>Parameterless anonymous method assigned to a delegate with different signature</b><br><hr>");

Response.Write("Name is Satheesh Babu");

};

DiffAnodel("Satheesh");

}

 

The output will be,

Parameterless anonymous method assigned to a delegate with different signature

Name is Satheesh Babu

 

Thus, we can define an anonymous method as a method without name which allows us to define the body inline.

 

Why should we use Anonymous method?

We can reduce the code by preventing delegate instantiation and registering it with methods..

It increases the readability and maintainability of our code by keeping the caller of the method and the method itself as close to one another as possible

 

Reference:

http://msdn2.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx


Downloads

Download Source
Article Feedback
Title  
Submitted By  
Comment  
Comments
Comments
the article is very useful to me.