简体   繁体   中英

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!

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.

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 .

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

Any other comments?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM