user2975866
user2975866

Reputation:

How to declare instance of delegate in C#?

private delegate void stopMachineryDelegate();
public stopMachineryDelegate StopMachinery;

this.StopMachinery += new stopMachineryDelegate(painting);

In the above example in the second line are we creating a delegate instance or a delegate variable? If the second line creates delegate instance of type stopMachineryDelegate, then in the third line what are we doing?

Upvotes: 1

Views: 761

Answers (2)

vgru
vgru

Reputation: 51214

First line is used to define your delegate type (stopMachineryDelegate), as a delegate accepting no parameters and returning no values (void).

Second line is declaring a field of that type, named StopMachinery. At that point, StopMachinery is null.

The third line has some syntactic sugar behind it. If StopMachinery is null at that point, it will create a new instance of that MulticastDelegate, and then add the painting method delegate to its invocation list.

If you only wanted to assign a single delegate to that field, you could have simply written:

 // implicitly wrap the `painting` method into a new delegate and 
 // assign to the `StopMachinery` field
 this.StopMachinery = painting;  

On the other hand, using += allows you to specify a list of delegates to be invoked when you invoke StopMachinery:

 this.StopMachinery += painting;  
 this.StopMachinery += someOtherMethod;  
 this.StopMachinery += yetAnotherMethod;  

In the latter case, invocation of the StopMachinery delegate will invoke each of the methods in the invocation list, synchronously, in the order they were specified.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

On the second line you are declaring a variable of type stopMachineryDelegate. But at this point the variable is still unassigned having holding a default value of null.

On the third line you are assigning a value to this variable by creating a new instance of the delegate pointing to the painting function.

So once this variable is assigned you could use it to invoke the function it is pointing to:

this.StopMachinery();

which will basically invoke the painting method in the same class.

Upvotes: 2

Related Questions