Sebastien Lachance

Exploring Anonymous Methods

My desire to explore Delegates and Anonymous Methods came from my next exploration, which will be the the Lambda feature. So, I will probably do an article on it in a near future.

So, what exactly is an anonymous method? It’s a C# 2.0 feature. Whenever you encounter the need to pass something as a delegate parameter, you can use an anonymous method.

Example :

This class has a method that expect a delegate that has no parameter and no return value.

public class Action
{
public delegate void MyActionDelegate();

public void Execute(MyActionDelegate myActionDelegate)
{
myActionDelegate.Invoke();
}
}

Previously, you would have declared a method that has no parameter and no return value and passed it to the Execute method. Like this :

public static void DoSomething()
{
Console.WriteLine("This is not an anonymous method.");
}

static void Main(string[] args)
{
Action action = new Action();

action.Execute(DoSomething);
}

An the output would be :

DelegateOutput

With an anonymous method, we reduce the code and by the same occasion, augment code readability.

static void Main(string[] args)
{
Action action = new Action();
action.Execute(delegate() { Console.WriteLine("This is inside an anonymous method."); });
}

AnonymousOutput

If the delegate has expected a parameter you could have done it like :

action.Execute(delegate(string s) { Console.WriteLine(s); });

And if the delegate have an return value, make sure you return one of the correct type :

action.Execute(delegate(string s) { return s; });

 

Accessing variables located outside the anonymous block :

A feature of an anonymous method is the ability to access variables located outside the anonymous scope (anonymous-method-block). Those variables called “outer variables”. It is better explained by an example :

string myString = "Outside the anonymous method.";
action.Execute(delegate(string s) { Console.WriteLine(myString); });

AnonymousScope

The exception to this rule are the ref and out parameters, which cannot be accessed by the anonymous method. You also can’t put unsafe code in the anonymous method.

Real life example

Maybe not (it’s always hard to come with great example), but it illustrate how you can use an anonymous method to find all string matching “String5” inside a collection of string. Just imagine doing the same thing in your collection of orders or products.

List<string> myListOfString = new List<string>();

for (int x = 0; x < 10; x++)
{
myListOfString.Add("String" + x);
}

List<String> returnedStrings = myListOfString.FindAll(delegate(string s) { return s == "String5"; });

 

Conclusion

Mastering Anonymous Methods is a great skill to have in you toolbox. But be careful, if you need to reuse the same code again and again, you better have to create a method and put the code in it. Don’t try to impress your friends too much. :)

Comments