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?

2
  • 12
    why have private methods when you can just make everything public and only call the necessary ones?
    – zxcvbnm
    Mar 28, 2010 at 5:41
  • The more that you can communicate your intent in your code, the more the compiler can cross-check for you, the easier it is for others to read and understand. There is also some additional potential optimization that can be done by the compiler. Mar 31, 2010 at 0:09

14 Answers 14

31

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

2
  • 1
    Interestingly you can modify readonly fields using reflection :)
    – Juliet
    Mar 28, 2010 at 8:01
  • 1
    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
    Mar 29, 2010 at 1:12
14

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!

2
  • 1
    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.
    – user88637
    Mar 28, 2010 at 7:49
  • 3
    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
    Mar 28, 2010 at 8:48
8

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.

1
  • 1
    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
    Mar 28, 2010 at 6:59
3

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.

2

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

2

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.

0
1

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.
1

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.

1

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.

1

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.

0

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.

2
  • You are talking about global variables, not const variables. I could do exactly what you've suggested without using the const keyword. Mar 28, 2010 at 4:39
  • 1
    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
    Mar 28, 2010 at 8:24
0

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

0

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.

-1

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.
2
  • 3
    Shouldn't that be for (int i=0; i<loopCount; i += one)?
    – Gabe
    Mar 28, 2010 at 4:44
  • 7
    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
    Mar 28, 2010 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.