Why can't I use String.Empty as a default parameter value?
Asked Answered
B

3

10

Today I was creating a default parameter value in a constructor.

public SomeClass (String something = String.Empty)
{
   // ...
}

The compiler complained.

Default parameter value for "something" must be a compile-time constant.

I was under the impression that Empty on the String class was a compile-time constant.

.field public static initonly string Empty

Am I missunderstanding the meaning of compile-time constant, or is it just more wackyness that I need to accept?

Betteanne answered 30/5, 2012 at 22:55 Comment(2)
The error message indicates your impression was 'erm not exactly correct.Lith
More complete discussion here: #508423Snaffle
E
4

The accepted answer to this SO Question Why isn't String.Empty a constant? is:

The reason that static readonly is used instead of const is due to use with unmanaged code, as indicated by Microsoft here in the Shared Source Common Language Infrastructure 2.0 Release. The file to look at is sscli20\clr\src\bcl\system\string.cs.

The Empty constant holds the empty string value. We need to call the String constructor so that the compiler doesn't mark this as a literal.

Marking this as a literal would mean that it doesn't show up as a field which we can access from native.

I found this information from this handy article at CodeProject.

Earthling answered 30/5, 2012 at 22:58 Comment(1)
I thought you are supposed to mark this as a duplicate? not give an answer.Fleet
D
2

A static readonly field is not a compile-time constant. It's just a static field, which should not change after the class in which it is finished initializing.

In the current .net implementation you can even change it with reflection, which leads to really weird behavior.

You can use "" instead, which as a string literal is a compile time constant.

Dyslogia answered 30/5, 2012 at 22:57 Comment(0)
N
1

A readonly field is a run-time constant. It won't be bound to a value until the object (or class, if the field is static) is initialized.

Compile-time constants are literals (such as "" - which essentially the same thing as String.Empty, anyway) and anything marked const.

Normy answered 30/5, 2012 at 22:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.