Monday, October 6, 2008

C# 2.0 - Anonymous methods


This blog post summarizes the new features of C# 2.0.

Below are the new features been introduced.

§ Partial Classes

§ Static Classes

§ Generic Classes

§ Anonymous methods

§ Iterators

§ Nullable Types

Anonymous methods

- In C# 1.x, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.

- Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.

- By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.

- Using anonymous methods can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when launching a new thread. See Code 2

- The local variables and parameters whose scope contain an anonymous method declaration are called Outer or Captured Variables of the anonymous method. For example, in the Code3 segment, n is an outer variable.

- Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. A reference to n is captured at the time the delegate is created.

- An anonymous method cannot access the ref or out parameters of an outer scope.

- No unsafe code can be accessed within the anonymous-method-block.

- See Code 4 –

1. Associating the delegate with an anonymous method.

2. Associating the delegate with a named method (DoWork).

- The parameter list of a delegate is compatible with an anonymous method if one of the following is true.

The anonymous method has no parameter list, and the delegate has no out parameters.

The anonymous method includes a parameter list that exactly matches the delegate’s parameters in number, types, and modifiers.

- The return type of a delegate is compatible with an anonymous method if one of the following is true.

The delegate’s return type is void, and the anonymous method has no return statements or only return statements with no expression.

The delegate’s return type is not void, and the expressions associated with all return statements in the anonymous method can be implicitly converted to the return type of the delegate.

Code 1 –

button1.Click += delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Click!"); };


// Create a delegate instance
delegate void Del(int x);
// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };

Code 2 –

void StartThread()
    System.Threading.Thread t1 = new System.Threading.Thread
                System.Console.Write("Hello, ");

Code 3 –

int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };

Code 4 –

// Declare a delegate

delegate void Printer(string s);

class TestClass


static void Main()


// Instantiate the delegate type using an anonymous method:

Printer p = delegate(string j)




// Results from the anonymous delegate call:

p("The delegate using the anonymous method is called.");

// Instantiate the delegate type using a named method "DoWork”

p = new Printer(TestClass.DoWork);

// Results from the old style delegate call:

p("The delegate using the named method is called.");


// The method associated with the named delegate:

static void DoWork(string k)






The delegate using the anonymous method is called.

The delegate using the named method is called.

Code 5 –

using System;

delegate double Function(double x);

class Test


static double[] Apply(double[] a, Function f)


double[] result = new double[a.Length];

for (int i = 0; i < a.Length; i++)


result[i] = f(a[i]);


return result;


static double[] MultiplyAllBy(double[] a, double factor)


return Apply(a, delegate(double x) { return x * factor; });


static void Main()


double[] a = {0.0, 0.5, 1.0};

double[] squares = Apply(a, delegate(double x) { return x * x; });

double[] doubles = MultiplyAllBy(a, 2.0);



Hope this helps

Thanks & Regards,

Arun Manglick || Senior Tech Lead

No comments:

Post a Comment