what is the difference between "static" and "const" when it comes to declare global variables;
namespace General
{
public static class Globals
{
public const double GMinimum = 1e-1;
public const double GMaximum = 1e+1;
}
}
which one is better (considering that these variables wont be changing ever)
namespace General
{
public static class Globals
{
public static double GMinimum1 = 1e-1;
public static double GMaximum1 = 1e+1;
}
}
A static keyword is been used to declare a variable or a method as static. A const keyword is been used to assign a constant or a fixed value to a variable. In JavaScript, the static keyword is used with methods and classes too. In JavaScript, the const keyword is used with arrays and objects too.
So combining static and const, we can say that when a variable is initialized using static const, it will retain its value till the execution of the program and also, it will not accept any change in its value.
Constant and ReadOnly keyword is used to make a field constant which value cannot be modified. The static keyword is used to make members static that can be shared by all the class objects.
The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object's entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.
const and readonly perform a similar function on data members, but they have a few important differences. A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.
The static modifier is used to declare a static member, this means that the member is no longer tied to a specific object. The value belongs to the class, additionally the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events
const
is a constant value, and cannot be changed. It is compiled into the assembly.
static
means that it is a value not related to an instance, and it can be changed at run-time (since it isn't readonly
).
So if the values are never changed, use consts.
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