Wednesday, 15 August 2007

Simple anonymous delegate

Although anonymous method has been supported by Java for a long long time, finally it comes to .NET 2.0. Here is a simple generic method:

public static void DoSomething<TObj>(IEnumerable<TObj> objs, Action<TObj> action){

foreach (TObj obj in objs)
action(obj);

}

We can pass in anonymous delegate for the action. The action represents a method that performs an action on the specified object. For example:

List<string> listOfStrings = new List<string>();
listOfStrings.Add("one");
listOfStrings.Add("two");
listOfStrings.Add("three");

AnonymousDelegate.DoSomething<string>(listOfStrings,
delegate(string s) { Response.Write(s + "<br/>"); });


The output in this example would be:

one
two
three

No comments:

Post a Comment