How to add methods to the invocation list of a delegate without instantiating the delegate?

412 Views Asked by At

I have to add multiple methods to the invocation list of a delegate. However, all of them have decision logic associated with them. So, there's an if block before the method gets attached to the invocation list of the delegate. Can I do this without instantiating the delegate. The code snippet looks like the following:

public delegate void SomeDelegate();

static void Method1() {}
static void Method2() {}

static void AddMethodsToInvocationList()
{
    SomeDelegate someDelegate = new SomeDelegate();
    if (someLogic1) someDelegate += Method1;
    if (someLogic2) someDelegate += Method2;
}

Basically, I wish to be able to create an instance of the delegate without passing any methods as parameters. However I get a compiler error with "does not contain a constructor that takes 0 arguments" error, if I try and instantiate the delegate without passing any methods as parameters.

I would also be open to solving this issue a different way if someone else has a better way of doing it. However, delegates have to be used.

Thank you for any help. Much appreciated.

1

There are 1 best solutions below

3
On BEST ANSWER

You can simply initialize it to null. That is the idiomatic value for a multicast delegate that doesn't have any operations added to it.