Before the 2.0 version of .NET, the C# language hasn’t other form for define a delegate than a named method. For instance, lets remember the design code for a windows application.

Introduction:

Before the 2.0 version of .NET, the C# language hasn’t other form for define a delegate than a named method. For instance, lets remember the design code for a windows application. As you could probably remember, every event ,used by the developer, auto generates a piece of code with a determine syntax, lets see an example.

Sample 1. Delegate use and declaration.

private void Form1_Load(object sender, EventArgs e)
        {
                   //code…
        } 

This little piece of code was call it every time the Load event of the form was call it, how?
Well, also the system generates a piece of code in the InitializeComponent() method assigning a new delegate to the event, as follows.

this.Load += new System.EventHandler(this.Form1_Load);

That was the only way to define a delegate, making a call to an existing method with the same parameters of the delegate, using the named method(method who has been call), as a parameter of the creation of the delegate.
But now pops a simple question, it’s necesary to define a method to add it to a delegate and then, if is need it, add it to an event too? (in the case of the latest sample occurs the three things).
.NET 2.0 gives us a computacional resource to solve this little issue. The anonymous methods.

Getting Anonymous:

Basically the anonymous methods creation is a form of passing a block code as a delegate’s parameter.

Lets think in the following situation. We are building an applications who needs to eliminate some values from some lists, but this lists are not made from the same type of object. A nice and elegant solution for this problem is to create a delegate for doing this, but that will lead us to build also a new method or several?

Lets get anonymous for solving our little problem.
Create a delegate call it Remove(IList list,object target)
and then assign the creation of the anonymous method to the variable rem
typed Remove .

Sample 2. 2.0 anonymous method.

public delegate void Remove(IList list,object target);
  .
  .
  .
List<int> list = new List<int>(new int[10] { 2,5,2,6,6,78,21,6,8,3});
             Remove rem = delegate(IList llist, object target)
             {
                 int tmp = llist.IndexOf(target);
                 if (tmp >= 0) llist.RemoveAt(tmp);
             };
             rem(list, 78);

with the delegate rem you will be able to eliminate any object from any list you want. This is a very simple and nice solution given for this problem, resumes a lot the code, making it more elegant, undertandable and reduce the references to code in other places.
Thru the anonymous methods you may reduce de codifications overloads thanks to the possibility of creating delegates with no need for a new independent method.
For instance, to declare a code block instead of a delegate may be usseful only when the creation of a delegate appears to be an innecesary overload.

Sample 3. Subprocces:

This class creates a subprocces and also have the code executed by the subprocces without the need of creating another method for the delegate.

void StartThread()
        {
            System.Threading.Thread t1 = new System.Threading.Thread
            (delegate()
            {
                System.Console.Write("Hello, ");
                System.Console.WriteLine("World!");
            });
            t1.Start();
        }

Variable Uses:

External variable: it’s a local  variable or parameter whose scope contains a declaration in an anonymous method. This variables may not be recover by the garbage collector untill the delegate containing the anonymous methods accomplish the requeriments to be recover. This means that while the delegate is been used so the external variable is. In the moment the delegate is created the variable’s value is capture.

Sample 4. External variable sample.

int n =1 ; Del d = delegate(string str)
            {
            Console.WriteLine("{0} has been written {1} times", str, ++n);
            };

Notices that the scope of the variable n will not be recovered by the garbage collector until the variable d (whose type is delegate) be ready to be recovered to. This is a classic sample of an external variable.

Syntax & Comments:

<delegate declaration>;
<delegate type> <variable name> = delegate(<parameters>*){ <implementation> };

*as in older versions of .NET the parameter’s type most be the same as the delegate’s declaration.

Sample 4. Syntax sample.
delegate void Del(string text);
Del d = delegate(string str)
{
Console.WriteLine(str + “this is a little sample.”);
};

It’s a tremendous error to use a jump instructions such as goto, break or continue in an anonymous block whose destiny is outside the block.
It’s also a greate error to use this same instructions in a block outside of the anonymous method whose destiny is inside the method.
Anonymous methods may not have acces to the ref or out parameters of an external scope. Also can’t acces to any unsecure code inside the anonymous-method-block.

Nicer Applications:

Delegates have been one of the most useful tools integrated to the .NET technology, especially to the C# language.  This computational resource allows to the developer to design very nice and understandable code, de reuse of it and, with anonymous methods, the possibility of threat methods as variables, and use it in different scopes according to his needs.  This characteristics makes, from the delegates, one of the most important resources in order to keep, and accomplish, the object oriented software constructions objective.
The anonymous methods are becoming the complement of the delegates, giving a better an nicer working face in order of  being more friendly for the developer. Nevertheless this does not mean that delegates now have to be only design and use with an anonymous method. The previuos way of use doesn’t die with this new one, only shines less.

Sample 6. Both ways for the use of delegates are good.

// Declare a delegate
delegate void Printer(string s);
class TestClass
{
 static void Main()
 {
 // Instatiate the delegate type using an anonymous method:
 Printer p = delegate(string j) { System.Console.WriteLine(j); };
 
// Results from the anonymous delegate call:
 p("The delegate using the anonymous method is called.");
 
// The delegate instantiation 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) { System.Console.WriteLine(k); }
}

Output
The delegate using the anonymous method is called.
The delegate using the named method is called.

Now on, you are very able to build more elegant solutions for very simple problems and reduce your code amounts, reducing the applications size. But is there the top of your curiosity.

Why, if this kind of method is so easy to use and so elegant,  is not used by the code generator of .NET for events declarations also in the form design?

 Good question ah?

Author:

Rancelinho: [email protected]
Mathematics and Computation Faculty
Havana’s University, Cuba.