0

I'm trying to create an array of delegates and wondering if I can do it without defining all the delegate methods in the class but as in methods that are then just stored in the array and passed out. Below is my attempt at the syntax but it isn't working. Is there a way to do this or is it a case that I have to define the methods conventionally in the class which is storing them in the array?

 delegate void myDelegateType();
 myDelegateType[] myDelegateArray = new myDelegateType[3];
 myDelegateArray[0] = new myDelegateType(void myMethod1(){int i = 0;});
user2457072
  • 173
  • 2
  • 8

2 Answers2

2

C# 2.0 introduced anonymous methods:

myDelegateArray[0] = new myDelegateType(delegate(){int i = 0;});

C# 3.0 introduced lambda expressions:

myDelegateArray[0] = new myDelegateType(() => {int i = 0;});

There is only minuscule difference between the two, but lambdas are typically preferred as they are easier to read & write.

Community
  • 1
  • 1
1

Its not called inline (that sounds like c #inline ) instead its called Lambda expressions. Here is the what it looks like:

delegate void myDelegateType();
static void Main(string[] args)
{
    myDelegateType[] myDelegateArray = new myDelegateType[3];
    myDelegateArray[0] = () => {int i = 0;};
}
madnut
  • 124
  • 5