tags:

views:

502

answers:

14

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?

+3  A: 

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.

Anthony Pegram
+2  A: 

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

Preet Sangha
+13  A: 

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!

ladenedge
I agree with your comments but you forgot to include maybe the most important reason for the existence of "const" : It allows the compiler to optimize the program.
Actually, I would submit that performance is the *worst* reason for using `const`. (Which is not to say that it isn't worth sacrificing maintainability for micro-optimizations in a tiny percentage of cases.)
ladenedge
+1  A: 

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.
Traveling Tech Guy
A: 

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.
xandy
Shouldn't that be `for (int i=0; i<loopCount; i += one)`?
Gabe
To be clear, xandy, you've still hard-coded the variable's value. You've just done so in a place that's far away from where the value is relevant, which could quite possibly be annoying. Blindly following a rule like "don't hard-code except in constants" can sometimes be worse than not following it at all.
ladenedge
+2  A: 

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.

kanchirk
Pi is an int? :-)
Ken
@kanchirk: There, I corrected it for you.
missingfaktor
@Rahul G / @Ken Thank you #lol
kanchirk
A: 

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.

Timothy Khouri
You are talking about global variables, not `const` variables. I could do exactly what you've suggested without using the `const` keyword.
Kirk Broadhurst
Yes, except marking it const informs both the compiler and the developer that the value is defined once, and is not something that can be changed over time.
kyoryu
+27  A: 

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 } }

Gabe
+1 for "directly into the compiled code".
ydobonmai
Interestingly you can modify `readonly` fields using reflection :)
Juliet
The choice const/readonly has versioning implications.
Henk Holterman
Henk has a good point. A `const` value is compiled in, so you can't change it in the source code without recompiling every module that references it. A `readonly` value is computed at runtime, so it can be freely changed in the source code.
Gabe
A: 

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' ;-).

isntn
+1  A: 

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.

Jay
+6  A: 

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.

JasonTrue
That sounds like a fun team. Also cheap, as you dont need visual studio - what for the debugger, you just type the code once in notepad (and let the secretary handle the comment spelling errors) ;) Real programmers dont need IDE's.
TomTom
A: 

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.

Amit
+1  A: 

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.

dan04
+1  A: 

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.

Sergey Teplyakov