开发者

What is the point of a constant in C#

Can anyone tell what is the point of a constant in C#?

开发者_运维百科For example, what is the advantage of doing

const int months = 12;

as opposed to

int months = 12;

I get that constants can't be changed, but then why not just... not change it's value after you initialize it?


If the compiler knows that a value is constant and will never change, it can compile the value directly into your program.

If you declare pi to be a constant, then every time it sees pi / 2 the compiler can do the computation and insert 1.57... directly into the compiled code. If you declare pi as a variable, then every time your program uses pi / 2 the computer will have to reference the pi variable and multiply it by 0.5, which is obviously slower.

I should also add that C# has readonly which is for values that the compiler cannot compute, but which cannot change for the duration of your program's execution. For example, if you wanted a constant ProgramStartTime, you would have to declare it readonly DateTime ProgramStartTime = DateTime.Now because it has to be evaluated when the program starts.

Finally, you can create a read-only property by giving it a getter but no setter, like this:

int Months { get { return 12; } } but being a property it doesn't have to have the same value every time you read it, like this:

int DaysInFebruary { get { return IsLeapYear ? 29 : 28 } }


The difference between "can't change" and "won't change" only really becomes apparent when one of the following situations obtains:

  • other developers begin working on your code,
  • third-parties begin using your code, or
  • a year passes and you return to that code.

Very similar questions arise when talking about data accessibility. The idea is that you want your code to provide only as much flexibility as you intend, because otherwise someone (possibly you) will come along and do something you did not intend, which leads to bugs!


If you never make mistakes, nobody on any team you work with ever makes mistakes, you never forget the exact purpose of a variable you've defined even after coming back to code you haven't looked at in months or years, and you and everyone you work with 100% reliably recognizes, understands and follows your intention of never changing a const value when you haven't bothered to use a built-in language construct that both clearly indicates and enforces constness, then no, there's no point.

If any one of those things ever turns out not to be the case, that's the point.

As for me, I find that even when I'm at my most lucid, remembering more than seven things at once is pretty close to impossible, so I'll take all the help I can get to prevent mistakes, especially when the cost is a single keyword. If you're smarter than me, and you never have to work on a team with someone less smart than you, then do whatever you want.

In some cases, there may be some compiler optimizations that can be done based on constness (constant folding, for one, which collapses expressions consisting of constants at compile-time). But usually, that's not the point.


Keep in mind you may not be the only person using the value. Not only can't you change it, but nobody using your code (as a library, for example) can change it.

And marking it as constant also makes your intent clear.


That's it. The you tell the compiler it can never change, and the compiler can optimise much better knowing that it is immutable.


Using constants programmers have the advantage of Readability over actual Value like

const double PI = 3.14159;

It also speeds up computation compared to variables by inserting values at compile time and not being inferred from a register/memory location.


For several reasons:

  1. You want to differentiate certain values that have certain meaning from other variables.
  2. You may later forget you are not meant to change a value, and cause unforeseen behavior.
  3. Your code may be used by other people an they may change it (especially if you're developing a library or an API).
  4. Because every thing that can go wrong usually will - so prevent it by making such errors discoverable at compile time rather than runtime.


Declaring a value 'const' brings the compiler into play to help you enforce personal discipline, by not allowing any changes to that value.

Also, it will catch unexpected errors due to side-effects of passing a value (that you intend to treat as a constant) into a method that takes a 'ref' parameter and could conceivably alter the value unexpectedly.


Strictly speaking, "const" isn't necessary. Python, for example, has neither "const" nor "private"; you specify your intent with the naming convention of THIS_IS_A_CONSTANT and _this_is_private.

C#, however, has a design philosophy of catching errors at compile time rather than runtime.


All about readability, different semantics for programmer is true and you should know all of it.

But constants in C# (rather in .net) has very different semantics (in terms of implementation) as compared with ordinary variables.

Because a constant value never changes, constants are always considered to be part of the defining type. In other words, constants are always considered to be static members, not instance members. Defining a constant causes the creation of metadata. When code refers to a constant symbol, compilers embed the value in the emitted Intermediate Language (IL) code.

These constraints mean that constants don’t have a good cross-assembly versioning story, so you should use them only when you know that the value of a symbol will never change.


The "point" is so that you can use a single program-wide variable and have only one spot to change it.

Imagine if you were making a video game that relied on knowing the FPS (frames per second) in 100 different code files. So pretend the FPS was 50... and you had the number "50" in all those files and functions... then you realize that you wanted to make it 60 FPS... instead of changing those 100 files, you would just change this:

const int FRAMES_PER_SECOND = 60;

and in those files / functions, you would use the FRAMES_PER_SECOND variable.

By the way, this has nothing to do with C#... constants are in tons of languages.


It is a case of being explicit of your intention.

If you intend to change value, then do not use 'const'. If you do not intend to change value, then use 'const'.

That way both compiler and third party (or yourself if you read your code after long time) can know what you intended. If you or somebody makes a mistake of changing value, then compiler can detect it.

And anyways, to use 'const' is not mandatory. If you think, you can handle 'constancy' yourself (without wanting compiler to detect mistake), then do not use 'const' ;-).


You should define a variable as "const" when you know the value of this will remain constant through out your application. So once you define a const, it value must be determinable at compile time and this value will be saved into the assembly's metadata. Some more important points abt Const:

  1. A const can be defined only for types your compiler treats as primary types.
  2. Constants are always considered to be the part of defining type.
  3. They are always considered to be Static members.
  4. Constants value are always embedded directly into the code, so constants dont require any memory to be allocated to them at run time.

Because of this embedding of the value into metadata, when somebody change the value of the const (in the assembly where the const is defined) due to versioning or some other requirement then the user of the dll has to recompile his own assembly. And this issue can be avoided using "readonly" keyword.


One of the rule that many programmers follow is: Never hard-code any variables / except 0. that means, instead of doing

for(int i=0; i<100; i++) {}

should do

const loopCount = 100;
....
for (int i=0; i<loopCount; i++) {}

I think using const is a good reason to replace this. And indeed, there's much more reason to this:

  1. Optimize for compiler - memory, performance.
  2. Tell the programmer that follow your work, this is CONSTANT
  3. If you need to refactor, change your mind in the number, you know where to go. And make sure no other places in the code would change this.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜