1

If a method in a class has a const variable such as:

public void MyMethod()
{
   const int myVariable = 5;

   // blah
}

will myVariable be initialized only once (when the method is called for the first time I believe) or everytime the method is called ?

1
  • Debug it and see for yourself. It is only set on the first call when the line is executed, and no more. I believe that the debugger will actually show how the line is being skipped on the second call (maybe even on the first call?) Commented Jun 8, 2013 at 21:09

2 Answers 2

11

Neither. Never. Constant are used primarily at compile time. It isn't a variable nor a field. The literal value 5 will be used by any code that uses the constant ("ldc.i4.5") - but the constant itself isn't needed for that at runtime.

Sign up to request clarification or add additional context in comments.

Comments

3

Never. What will happen is that the compiler will burn in that variable into the method: as if it never existed, and just put the value where you put the const's name.

e.g.

public double MyMethod()
{
    const int anInt = 45;
    return anInt * (1/2.0) + anInt;
}

will get compiled to:

public double MyMethod()
{
    return 45 * (1/2.0) + 45; 
    //actually that would also be calculated at compile time,
    //but that's another implementation detail.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.