CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Delegates and Anonymous methods in C#

By Satheesh babu
Posted On Feb 18, 2008
Article Rating:
Be first to rate
this article.
No of Comments: 21
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
Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Simple and easy understanding
Neatly explained
Nice article
Useful and easy to understand... thanks..
Good Article
Very good article.Easy to understand.
Easy to Understand
Hi, Many thanks for this article, As i was searching for this type of easy understandable article. You saved My time a Lot.
good
gOOD ARITICLE BUT WE NEED SOME MORE REAL TIME EXAMPLES .
Simple to understand
it's really simple to understand,also the presentation of example is simply good
Awesome explanation
its really really nice
Nice
This article helps me to understand about both delegate and anonymous method concepts, also useful to new learners
Good
Very easy way of explain, very helpfull. it has the diff b/w deligate and anonymous methods in term of variable access :-)
Good Article
very help full to understand the anonymous method & delegate
Superb
It is really very nice to understand the function pointer delegates multicast delegate anonymous methods.
thank you
Mr
Simply superb...
Fantastically Simple
Extremely nice and simplified way of explaining.. Function pointer was one concept.. I always use to skip because it didnt make sense to me.. but this article changed it..
Excellent
very helpful topic, and a good description about anonymous methods
venkat
very good and simple way explanation. keep it up.thank u.
Excellent
Excellent. This article helps me to understand Anonymous methods and it uses and different way of using it. This type of article will helps the freshers who are new to .Net 3.5 to grow up.
Informative ideas
useful.....
Informative Article
Good work :)
Atricle is very useful
Userful to me
Nice Article
It is clear and very helpfull. Good work
Comments
the article is very useful to me.