Defining and Using Constants

When you hard-code numbers in your code (such as in intVotingAge = 19;), a myriad of things can go wrong. Hard-coded numbers are generally referred to as “magic numbers” because they're often shrouded in mystery; the meaning of such a number is obscure because the digits themselves give no indication as to what the number represents. Constants are used to eliminate the problems of magic numbers.

You define a constant as having a specific value at design time, and that value never changes throughout the life of your program. Constants offer the following benefits:

  • Elimination or reduction of data entry problems It is much easier, for example, to remember to use a constant named c_pi than it is to enter 3.14159265358979 ...

Get Sams Teach Yourself C#™ in 24 Hours now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.