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?
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.
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.
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:
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With