Computer Science Canada

C# Delegates

Author:  rdrake [ Tue Sep 04, 2007 10:26 pm ]
Post subject:  C# Delegates

Fun stuff:
code:
using System;

class Program
{
    delegate double multiplyByTwo(double value);

    public static void Main()
    {
        multiplyByTwo mbt = delegate(double value)
        {
            return value * 2;
        };

        Console.WriteLine(mbt(2.0));
    }
}
Shows an example of an anonymous method as well.

As you might have guessed, it outputs 4.

Author:  wtd [ Wed Sep 05, 2007 12:47 am ]
Post subject:  RE:C# Delegates

I don't have access to Mono 1.2.5 at the moment, but would the following work?

code:
using System;

class Program
{
    delegate double multiplyByTwo(double value);

    public static void Main()
    {
        multiplyByTwo mbt = v: double => v * 2;

        Console.WriteLine(mbt(2.0));
    }
}

Author:  rdrake [ Wed Sep 05, 2007 11:17 am ]
Post subject:  RE:C# Delegates

With some minor modifications it will work under C# 3.0:

code:
using System;

class Program
{
    delegate double multiplyByTwo(double value);

    public static void Main()
    {
        multiplyByTwo mbt = (v) => v * 2;

        Console.WriteLine(mbt(2.0));
    }
}
C# 2.0 lacks the ability to make use of implicitly typed parameters.


: