
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Using Anonymous Methods
|
539
Notice that all that is assigned to the DoWork delegate instance dw is the method name
DoWorkMethodImpl. There is no “new DoWork(DoWorkMethodImpl)” call as there was in
older C# code.
Remember, the underlying delegate wrapper does not go away, dele-
gate inference just simplifies the syntax a bit by hiding some of it.
Alternatively, you can also set up anonymous methods that take generic type param-
eters to enable working with generic delegates as you do here in the
GenericWay class:
class GenericWay
{
// Declare generic delegate.
delegate T DoGenericWork<T>(T t);
// Have a method to create two instances of and call the delegates.
public void WorkItOut( )
{
DoGenericWork<string> dwString = delegate(string s)
{
Console.WriteLine(s);
return s;
};
// Invoke string delegate.
string retStr = dwString("DoWorkMethodImpl1");
DoGenericWork<int> dwInt = delegate(int i)
{
Console.WriteLine(i);
return i;
};
// Invoke int delegate.
int j = dwInt(5);
}
}
The DoGenericWork delegate is defined with one type parameter, T, which is used to
specify the type of the returned value as well as the single parameter passed. Setting
up the delegate this way allows the
WorkItOut method to create two instances of
DoGenericWork, one using string and the other using int as the type.