Thursday, October 09, 2008

Delegates

Covariance : a method can return a type that is derived from the delegate's return type.

Contra-variance : a method can take a parameter that is a base of the delegate's parameter type.

ex. delegate object MyCallback(FileStream s);
can bound to string SomeMethod(Stream s);

Covariance and Contra-variance are supported only for reference types, not for value types or void.

Shortcuts while working with delegates:

  • If a function expects delegate, just pass function name.
  • use anonymous method to create delegate.
  • don't specify callback method parameters, if you don't need
  • delegate method can use local variables of the invoking method.

ex. We have a delegate as follows, and the function which accepts the delegate :

delegate void TheDelegate(object o);
static void ProcessFunction(TheDelegate d,object o)
{
  d(o);
}

int x = 0;
ProcessFunction(Foo, 5);
ProcessFunction(delegate(object o){
  Console.WriteLine("Anonymous method");}, 5);
ProcessFunction(delegate{
  Console.WriteLine("Simpler Anonymous method");}, 5);
ProcessFunction(delegate{
  Console.WriteLine("Modifying local x to 9"); x = 9;}, 5);
Console.WriteLine("Value of x : " + x);

No comments: