Search code examples
c#methodsconstants

C# Initializing a const variable in a method


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 ?


Solution

  • 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.