how to convert optional parameter method to delegate in c#

i have a casting problem.

public void Test(int a = 0) { }

System.Action d = Test;

this code works well in unity 5.

but visual studio 2015 can't compile it.

CS0123 No overload for 'Test' matches delegate 'Action'

why???

Jon Skeet
people
quotationmark

I'm surprised it works in Unity - it shouldn't. That sounds like a Mono compiler bug.

The C# 5 specification isn't as clear on this as it should be, but from the draft of the upcoming ECMA C# 5 standard, from the clause on method group conversions - emphasis mine:

  • A single method M is selected corresponding to a method invocation of the form E(A), with the following modifications:
    • The argument list A is a list of expressions, each classified as a variable and with the type and modifier (ref or out) of the corresponding parameter in the formal-parameter-list of D – excepting parameters of type dynamic, where the corresponding expression has the type object instead of dynamic.
    • The candidate methods considered are only those methods that are applicable in their normal form and do not omit any optional parameters. Thus, candidate methods are ignored if they are applicable only in their expanded form, or if one or more of their optional parameters do not have a corresponding parameter in D.

The simplest fix is to use a lambda expression, as Dai says:

Action d = () => Test();

people

See more on this question at Stackoverflow