Ankit Rana
Ankit Rana

Reputation: 383

Why string type allows to use as constant?

Why string type allows to use as constant?

Because the string gets initialise in heap so how they can use as constant. how does the compiler know the size of the string? and what is string table ? is that used for calculating the string length.

if I used the string constant many places in the application, does it increase the memory consumption?

Upvotes: 0

Views: 132

Answers (3)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

The .NET team could have gone ahead and allowed arbitrary expressions to be used as constants — e.g. new Vector2(0, 0) if the Vector2 constructor was known to have no external side effects and the type was known to be a struct or otherwise immutable. But they simply didn't take the time to do this, perhaps because figuring out these requirements is extra work for the compilers (remember, C# has no immutable or pure keywords yet).

The string type is special to the compiler and the runtime: it was designed from the start to be immutable and its constructors have no externally observable side-effects, so the creators of the .NET runtime baked this knowledge into the compiler. That's why string has literals and gets special treatment.

Still, they probably wanted to avoid teaching the infrastructure too many special types — just a handful of fundamental types, namely primitives and strings. DateTime simply wasn't deemed important enough to be included.

Upvotes: 5

Joe Phillips
Joe Phillips

Reputation: 51100

Because a const string is not treated as a reference, it becomes a literal.

Upvotes: 1

user47589
user47589

Reputation:

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

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.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const

Strings can be fully evaluated at compile time. DateTimes cannot.

Upvotes: 3

Related Questions