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?

1
  • If my answer below solved your issue please indicate so. Commented May 15, 2016 at 23:24

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

<cough> null coalescing operator </cough>
@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.
?? is the null coalescing operator. There is no need but it is neater and more concise, right?
@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.
Fortunately the c# and CLR teams thought of this and there's an IL instruction for it: stackoverflow.com/questions/13385503/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.