views:

334

answers:

3

In this snippet:

class ClassWithConstants
{
    private const string ConstantA = "Something";
    private const string ConstantB = ConstantA + "Else";

    ...

}

Is there a risk of ending up with ConstantB == "Else"? Or do the assigments happen linearly?

+3  A: 

this string concatenation happens at compile-time because there are only string literals (search for constant folding in compiler construction literature).

Don't worry about it.

dfa
+2  A: 

It should always evaluate to "SomethingElse"

Jimmeh
+30  A: 

You will always get "SomethingElse". This is because ConstantB depends upon ConstantA.

You can even switch lines and you'll get the same result. The compiler knows that ConstantB depends upon ConstantA and will handle it accordingly, even if you write it in partial classes.

To be completely sure you can run VS Command Prompt and call ILDASM. There you can see the actual compiled code.

Additionally, if you try to do the following you'll get a compile error:

private const string ConstantB = ConstantA + "Else";
private const string ConstantA = "Something" + ConstantB;

Error: The evaluation of the constant value for 'ConsoleApplication2.Program.ConstantB' involves a circular definition This sort of proves the compiler knows its dependencies.


Added: Spec reference pointed out by Jon Skeet:

This is explicitly mentioned in section 10.4 of the C# 3 spec: Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order.


Luis Filipe
Yup, you're right - doh! :) Trying to find the bit in the spec which guarantees this...
Jon Skeet
Found it now - section 10.4.
Jon Skeet
Edited my answer so at least it's not going to mislead people, but will delete it if/when I can.
Jon Skeet
This is nice. I am pretty sure Java's compilers don't do any such thing, and it's based only on the ordering.
Mike Daniels