C# – Action returning void and taking parameter, with ternary operator

c

I want to write an Action which only takes a PerformanceCounterCategory as a parameter. I know there is Action<>, Func<> and Delegates and there is some distinction between these, but I am not sure what it is. Can someone please tell me what the difference is (I read somewhere that Action does not return, or this may be Func).

I am trying to write something like the following:

Action<PerformanceCounterCategory> action = (int > 5) ? action1 : action2;

action1 and action2 are both methods which return void but take PerformanceCounterCategory as the (only) parameter.

Is this the right way to go? I keep getting errors about method group/void etc so I am not confident the code above is the best for my needs.

Thanks

Best Answer

You'll need to cast one side or other - or not use the conditional operator.

Basically, ignore the assignment - because the compiler does. It doesn't use the fact that you're trying to assign to a variable to work out the type of the conditional expression. We're left with just:

(i > 5) ? action1 : action2

as the expression. What's the type of that? What delegate type should the method groups be converted to? The compiler has no way of knowing. If you cast one of the operands, the compiler can check that the other can be converted though:

(i > 5) ? (Action<PerformanceCounterCategory>) action1 : action2

Alternatively:

Action<PerformanceCounterCategory> action = action2;
if (i > 5)
{
    action = action1;
}

It's unfortunate, but that's life I'm afraid :(