I want to create a delegate type in C# inside a method for the purpose of creating Anonymous methods.
For example:
public void MyMethod(){ delegate int Sum(int a, int b); Sum mySumImplementation=delegate (int a, int b) {return a+b;} Console.WriteLine(mySumImplementation(1,1).ToString()); }
Unfortunately, I cannot do it using .NET 2.0 and C# 2.0.
In C# 3.0 and later, delegates can also be declared and instantiated by using a lambda expression, as shown in the following example. // Instantiate Del by using a lambda expression. Del del4 = name => { Console. WriteLine($"Notification received for: {name}"); };
Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class. There are three steps in using delegates. These include declaration, instantiation, and invocation.
Why do you want to create the delegate type within the method? What's wrong with declaring it outside the method? Basically, you can't do this - you can't declare a type (any kind of type) within a method.
One alternative would be to declare all the Func/Action generic delegates which are present in .NET 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 are on my C#/.NET Versions page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With