5

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!

Community
  • 1
  • 1
One Monkey
  • 713
  • 3
  • 9
  • 24

3 Answers3

11

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.

pdr
  • 6,372
  • 1
  • 29
  • 38
5

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

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

Any other comments?

One Monkey
  • 713
  • 3
  • 9
  • 24
  • @Saif al Harthi: "Wouldn't you know it" is simply an expression of surprise. – BoltClock Dec 18 '10 at 12:27
  • Modify your question to include "static readonly", include short summary of the article here and I can up vote your answer. – agsamek Dec 18 '10 at 12:37