Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of a constant in C#

Tags:

c#

constants

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?

like image 794
Adam Avatar asked Mar 28 '10 04:03

Adam


People also ask

What is the purpose of a constant?

Constants are useful for defining values that are used many times within a function or program. For example, in the C++ code below, min and max are declared as constants.

What is the value of C constant?

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.


2 Answers

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

like image 96
Gabe Avatar answered Sep 21 '22 06:09

Gabe


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!

like image 41
ladenedge Avatar answered Sep 22 '22 06:09

ladenedge