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.

Etheryte
  • 24,589
  • 11
  • 71
  • 116

1 Answers1

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964