Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a delegate type inside a method

Tags:

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.

like image 946
Nikola Stjelja Avatar asked Dec 11 '08 13:12

Nikola Stjelja


People also ask

Can we declare delegate inside class C#?

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}"); };

How do you call a delegate method in C#?

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.

What are delegate methods and its type?

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.

CAN is delegate declared within class?

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.


1 Answers

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.

like image 172
Jon Skeet Avatar answered Sep 19 '22 18:09

Jon Skeet