[ACCEPTED]-Creating a delegate type inside a method-delegates

Accepted answer
Score: 26

Why do you want to create the delegate type 8 within the method? What's wrong with declaring 7 it outside the method? Basically, you can't 6 do this - you can't declare a type (any kind 5 of type) within a method.

One alternative 4 would be to declare all the Func/Action 3 generic delegates which are present in .NET 2 3.5 - then you could just do:

public void MyMethod(){
    Func<int, int, int> mySumImplementation = 
        delegate (int a, int b) { return a+b; };

    Console.WriteLine(mySumImplementation(1,1).ToString());
}

The declarations 1 are on my C#/.NET Versions page.

Score: 17

The delegate type has to be defined outside 9 the function. The actual delegate can be 8 created inside the method as you do.

class MyClass {
  delegate int Sum(int a, int b);
  public void MyMethod(){

       Sum mySumImplementation=delegate (int a, int b) {return a+b;}

       Console.WriteLine(mySumImplementation(1,1).ToString());
  }

}

would 7 be valid. The best solution may be to emulate 6 .NET3.5, and create some generic delegate 5 types globally, which can be used all over 4 your solution, to avoid having to constantly 3 redeclare delegate types for everything:

delegate R Func<R>();
delegate R Func<T, R>(T t);
delegate R Func<T0, T1, R>(T0 t0, T1 t1);
delegate R Func<T0, T1, T2, R>(T0 t0, T1 t1, T2 t2);

Then 2 you can just use a Func<int, int, int> delegate in your code 1 above.

Score: 6

Delegates are compiled to classes(a class 4 that inherits from System.MulticastDelegate). In 3 C#, you are not allowed to declare a class 2 inside a method(see C# language specification). Thus 1 you can't declare a delegate in a method, either.

Score: 0

What about this:

static void Main(string[] args)
{
    Expression<Func<int, int, int>> exFunc = (a, b) => a + b;
    var lambda = exFunc as LambdaExpression;
    Delegate del = exFunc.Compile();
    Console.WriteLine(del.DynamicInvoke(2, 2));
}

0

More Related questions