Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between static and const variables [duplicate]

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;
    }
}
like image 340
Ibrahim Ozdemir Avatar asked May 28 '15 20:05

Ibrahim Ozdemir


People also ask

What is the difference between a static and const variable?

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.

Can a variable be both const and static?

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.

What is difference between static and constant variable in C#?

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.

What is the difference between static final and const?

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.


2 Answers

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

like image 79
Benjamin RD Avatar answered Sep 18 '22 23:09

Benjamin RD


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.

like image 24
Maarten Avatar answered Sep 21 '22 23:09

Maarten