If I am using a constant that is needed only in a method, is it best to declare the const within the method scope, or in the class scope? Is there better performance declaring it in the method? If that is true, I think it's more standard to define them at class scope (top of file) to change the value and recompile easier.
public class Bob { private const int SomeConst = 100; // declare it here? public void MyMethod() { const int SomeConst = 100; // or declare it here? // Do something with SomeConst } }
The difference is that #define is processed by the preprocessor doing what amounts to simple text replacement. Const values defined like this are not visible for the actual compiler, while a variable defined with the const modifier is an actual typed "variable" (well not really that variable).
In general, const is a better option if we have a choice and it can successfully apply to the code. There are situations when #define cannot be replaced by const. For example, #define can take parameters (See this for example). #define can also be used to replace some text in a program with another text.
If you declare a local variable const , you simply mark it immutable. It should never ever change its value. If you still try to modify it later on, you'll get a compilation error. For global variables, this is rather useful, as otherwise, you have no idea who can modify their value.
The const keyword is used to modify a declaration of a field or local variable.
There is no performance gain in moving the constant into the class. The CLR is smart enough to recognize constants as constant, so as far as performance goes the two are equal. What actually happens when you compile to IL is that the values of the constants are hardcoded into the program by the compiler as literal values.
In other words, a constant is not a referenced memory location. It is not like a variable, it's more like a literal. A constant is a literal synced across multiple locations in your code. So it's up to you - though it's neater programming to limit the scope of the constant to where it is relevant.
Depends on if you want to use it throughout your class. The top declaration will be usable throughout your class whereas the other will only be available in MyMethod
. You won't get any performance boost by doing it either way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With