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?
精彩评论