0

I have the following little piece of code that left me somewhat baffled since I'm not all that familiar with C#.

I need to use an optional parameter as shown below:

private string GetSomething(object inputObject, string optionalString = "")
{
    //...
}

All's swell and well. However, if I edited the above piece to follow the coding standard of the rest of the project, as shown below, I got an error:

private string GetSomething(object inputObject, string optionalString = String.Empty)
{
    //...
}

With the error reading

Default parameter value for 'optionalString' must be a compile-time constant.

While I understand why it needs to be a constant, why isn't the latter version simply optimized away and compiled like the first version? Is there a difference in some circumstances?
If it matters, I'm using Visual Studio 2013, the project is .NET 4.5.

0

1 Answer 1

6

For complicated reasons, String.Empty is not a compile-time constant; instead, it's a read-only field.

The JITter will optimize out all references to it, but the C# language does not treat it as a constant.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.