You can declare a constant inside a function.
When you wrote
public int SomeMethod(int a) {
const int SomeCompileTimeConstant = 10; // obviously this doesn't exist
return a + SomeCompileTimeConstant;
}
you were wrong.
Question
Is there any way to limit the scope of a compile-time constant to a method/block of code that avoids hardcoding the value?
Something like the following:
public int SomeMethod(int a) {
const int SomeCompileTimeConstant = 10; // obviously this doesn't exist
return a + SomeCompileTimeConstant;
}
opposed to hardcoding the value:
public int SomeMethod(int a) {
return a + 10;
}
or making it a class-level constant:
public class A {
private const int SomeCompileTimeConstant = 10;
public int SomeMethod(int a) {
return a + SomeCompileTimeConstant;
}
}
La solution
You can declare a constant inside a function.
When you wrote
public int SomeMethod(int a) {
const int SomeCompileTimeConstant = 10; // obviously this doesn't exist
return a + SomeCompileTimeConstant;
}
you were wrong.