flockofcode
flockofcode

Reputation: 1819

Why are member constants available even if there are no instances of a its class?

1) Why are member constants available even if there are no instances of a its class?

2) Is the only reason why constant expressions need to be fully evaluated at compile time due to compiler replacing constant variable with literal value?

3) Since string is also an object, I would think the following would produce an error, but it doesn’t. Why?

class A
{
    const string b = “it works”; 
}

thank you

Upvotes: 1

Views: 156

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

  1. Constants (declared with const) are implicitly static - hence no need for an instance.

  2. A const value is embedded in the assembly it's declared in, and then every time it's used, that value is copied into the calling code as well. Therefore it can't be evaluated at execution time - if you want that behaviour, use static readonly.

  3. String literals are constant values according to the C# language specification. Basically IL has a metadata representation for strings, allowing them to be specified as constants. String constants also have other interesting properties such as interning.

One point of interest: you can declare a decimal field as const in C#, but that doesn't really have CLR support... there's no literal form. The C# compiler fakes it using the [DecimalConstant] attribute. That's why you can't use decimal as an attribute argument type.

Upvotes: 8

Related Questions