Delegate Inference


C# 2.0 extends the syntax with delegates by delegate inference. At every place where a delegate instance is needed, you can just pass the name of the address. The previous example initialized the variable firstStringMethod of type GetAString with a new instance of the delegate GetAString:

  GetAString firstStringMethod = new GetAString(x.ToString); 

You can write the same just by passing the method name with the variable x to the variable firstStringMethod:

  GetAString firstStringMethod = x.ToString; 

The code that is created by the C# compiler is the same. The compiler detects that a delegate type is required with firstStringMethod, so it creates an instance of the delegate type GetAString and passes the address of the method with the object x to the constructor.

Tip 

Be aware that you can’t invoke the method x.ToString() and pass it to the delegate variable. Invoking x.ToString() returns a string object that can’t be assigned to the delegate variable. You can only assign the address of a method to the delegate variable.

Delegate inference can be used at any place where a delegate instance is required. Delegate inference can also be used with events because events are based on delegates (as you can see later in this chapter).




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net