Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Local Variable const vs Class const

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    } } 
like image 530
Stealth Rabbi Avatar asked Jun 16 '11 13:06

Stealth Rabbi


People also ask

When to use #define vs const?

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

Is const better than #define in C?

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.

What is const local variable?

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.

How can we declare a local variable as constant?

The const keyword is used to modify a declaration of a field or local variable.


2 Answers

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.

like image 193
jnm2 Avatar answered Sep 21 '22 15:09

jnm2


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.

like image 45
Neil Knight Avatar answered Sep 18 '22 15:09

Neil Knight