Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# What is the difference between static and constant?

As it says. I am about to define a constant, or static, value in a program I am writing and am confused as to why you would use one or the other. As the only related question i get when asking this question deals with someone who wants to mark something as both static and constant at once I suspect I am not the only person a bit lost with these concepts.

So why would I use static and why would I use constant? What's the distinction? Are they synonymous? If so, that's cool, but if not why not? Thanks!

like image 397
One Monkey Avatar asked Dec 18 '10 12:12

One Monkey


3 Answers

const is dealt with at compile time. Every reference to that constant is replaced by the constant value.

static is very different. It is a variable which exists only once but belongs to all objects of that type. It can be edited unless marked as readonly (or given a getter but no setter). If it is marked as readonly then it is essentially a constant, but it is handled at runtime, not by the compiler.

like image 169
pdr Avatar answered Oct 03 '22 22:10

pdr


First off, they are not synonymous.

  • static marks a member as belonging to the type.
  • const means the member value cannot be changed. The value is determined at compile time and substituted wherever it appears.

For better understanding of how static is to be used, read Static Classes and Static Members.

like image 45
Oded Avatar answered Oct 03 '22 23:10

Oded


And wouldn't you know it five minutes later I find this.

Any other comments?

like image 22
One Monkey Avatar answered Oct 03 '22 23:10

One Monkey