Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Const and Static in C#?

Tags:

c#

I am eager to know the difference between a const variable and a static variable.

As far as I know a const is also static and can not be accessed on instance variable that's same like static , then what is the difference between them ?

Please explain ...

like image 937
Embedd_0913 Avatar asked Mar 25 '10 03:03

Embedd_0913


People also ask

What is the difference between const and static?

Static is a storage specifier. Const/Constant is a type qualifier. Static can be assigned for reference types and set at run time. Constants are set at compile-time itself and assigned for value types only.

Is it static const or const static?

They mean exactly the same thing. You're free to choose whichever you think is easier to read. In C, you should place static at the start, but it's not yet required.

What is constant and static variable?

Constant variables never change from their initial value. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops.

What is the difference between const and static readonly?

The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.


1 Answers

const fields can only hold value types or System.String. They must be immutable and resolvable at compile-time.

static readonly fields can and generally do hold reference types, which (other than strings) can only be created at runtime. These can (but shouldn't) be mutable types; the only thing that cannot change is the reference itself.

If you need to maintain a "constant" set of instances that are reference types, you generally do it with a set of public static readonly fields, such as the members of System.Drawing.SystemColors.

Last but not least, initialization of a readonly field can be deferred until the execution of a constructor, which means that it even though it can only be written to once, it does not always have to be initialized with the exact same value. True constants declared with const can only ever have a single value (specified at compile time).

like image 73
Aaronaught Avatar answered Sep 25 '22 19:09

Aaronaught