Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can string that is a reference type be a non-null const while other reference type consts must be null?

Tags:

c#

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)?

like image 979
kiss my armpit Avatar asked Jul 10 '14 10:07

kiss my armpit


Video Answer


4 Answers

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 = ???).

like image 93
Matthew Haugen Avatar answered Oct 13 '22 11:10

Matthew Haugen


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.

like image 24
usr Avatar answered Oct 13 '22 12:10

usr


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.

like image 23
AlexD Avatar answered Oct 13 '22 11:10

AlexD


According to MSDN:

Constants can be numbers, Boolean values, strings, or a null reference.

like image 33
decPL Avatar answered Oct 13 '22 11:10

decPL