0

I have a class and function

class A
{
    A(int i = 0)
    {
    }
}

void f(A a = new A(10)) // ? default parameter value must be compiler-time constanct
{
}

How to workaround it?

user1899020
  • 13,167
  • 21
  • 79
  • 154

1 Answers1

2

You would need to do it inside the method and provide a comment that the method accepts null and uses A(10) as a default value.

void f(A a = null)
{
    if(a == null)
        a = new A(10);
}
Matt Rowland
  • 4,575
  • 4
  • 25
  • 34
  • null coalescing operator – Slugart May 15 '16 at 20:25
  • @Slugart That wouldn't work because the assignment only needs to be made if the object is `null`. You could use `a = a ?? new A(10);` but there is no need. – Matt Rowland May 15 '16 at 20:27
  • 1
    ?? is the null coalescing operator. There is no need but it is neater and more concise, right? – Slugart May 15 '16 at 20:35
  • @Slugart If the parameter is not `null` it will do the assignment still. It is an operation that doesn't need to happen. By doing the null check the assignment will only happen if a null is passed; or in this case by default. – Matt Rowland May 15 '16 at 20:38
  • Fortunately the c# and CLR teams thought of this and there's an IL instruction for it: http://stackoverflow.com/questions/13385503/which-works-faster-null-coalesce-ternary-or-if-statement – Slugart May 16 '16 at 06:31
  • @Slugart That answer only addresses assigning a _different_ variable a value based on the first; not assigning the first based on the first. – Matt Rowland May 16 '16 at 14:40