As far as I know, string
is a reference type. const
can be used with reference
type only if they are assigned null
. My question is that
why can string
which is a reference type can be assigned a literal string (or non-null)?
Taken from the const documentation:
A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.
In other words, it's an exception. Life would be a whole lot more difficult if there weren't such things as string constants.
You can also remember that it's not all strings, for instance you can't compile with the code const string test = new string('t', 7);
, even though you could with static string test = new string('t', 7);
. On the other hand, while you can define a string constant as a string literal (test = "value";
), you can't define any other reference types with a literal (Form f = ???
).
This is a special rule in the C# language and a feature of the CLR. The compiler knows how to embed strings into the assembly meta-data.
ECMA-334 C# Specification has the following note (emphasis mine):
As described in §14.16, a constant-expression is an expression that can be fully evaluated at compiletime. Since the only way to create a non-null value of a reference-type other than string is to apply the new operator, and since the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.
According to MSDN:
Constants can be numbers, Boolean values, strings, or a null reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With