Göran Andersson said:
Yes, the literal strings are created when the assembly loads, so the
exist all the time the application does.
However, calling strings constant objects is somewhat misleading, as
constants doesn't exist at all. A constant is just a name defined at
compile time, they never exist as variables at runtime.
I agree. It's important to distinguish between "constant" and
"immutable", mainly because C# has a specific concept of "constant"
(i.e. "const"). I mean, I suppose you could use the word "constant" to
describe a type that is immutable, but that can lead to communication
problems, since you'd be using different jargon from what everyone else
is using.
Also, you can have a constant of the type string, which is a bit of a
special case. It's the only reference type that can be a constant, and
it's only the string literal that exists.
In particular, this is allowed _because_ the object can be known at
compile time. Any constant has to have a known value at compile time,
so other reference types – requiring the execution of a constructor at
run-time in order to exist – cannot be used for constants. String
literals are treated as having been constructed at compile-time and so
there's a kind of reference that can be resolved at compile time for
string constants.
Basically, strings behave as much as a primitive value type as they do
the reference type that they really are, and so in the language they get
special treatment to allow things that wouldn't be allowed for other
reference types. Of course, the immutability of the string type is a
very important aspect of this; a mutable string type (e.g.
StringBuilder) couldn't support the kind of compile-time features that
System.String can.
The constant is still just a
name that exist at compile time.
I guess that depends on your definition of "exist". A public constant
declared in a given assembly is still visible in that assembly after
compilation. To me, that's "existence" of a sort.
But yes, inasmuch as there is no variable per se that is referenced when
your code uses a constant – the value of the constant is simply
hard-coded into the code – the constant doesn't exist after compilation.
But according to that definition of "exist", I'd say it doesn't exist
at compile time either.
IMHO, the important thing about constants – as opposed to worrying about
how they are implemented – is that they are "baked" into the code. Once
your code is compiled, if it used a constant declared in a different
assembly, even if that assembly is recompiled with a different value of
the constant, your own assembly will not use the new, different value.
It's that "non-variable" behavior that IMHO sets constants apart from
other value identifiers.
Pete