May 13th, 2009, 12:54 AM
Enum & Constant
What's the difference between enum and constant?Are they useful in real-life programming? or do they exist solely to make coding more tidy? Do they serve any real purpose?
May 13th, 2009, 01:13 AM
Re: Enum & Constant
A constant is like a variable except its value is constant instead of being variable. You could use variables instead of constants but using a constant doesn't rely on your honesty to not change the value. It just won't let you. When a value doesn't change it's a good idea to use a constant rather than a variable to store it, especially if it's being exposed beyond the type it's declared in.
An enumeration is designed in such a way as to make life easier for the developer and the computer. Internally enumerated values are represented as numbers rather than strings, so they are easier and faster for the machine to deal with. In code though, they are represented by a text label (but NOT a string) that makes them far more meaningful to the developer. For instance, it's far easier to work with the values OK, Cancel, etc. being returned by MessageBox.Show than working with the numbers 0, 1, etc. and remembering what they mean.
Enumerations are also good because they limit the set of legal values. Enumerations are fully-fledged types, so where a variable is declared as type DialogResult you will be limited by the compiler to using the legal values OK, Cancel, etc. If you were to use the Integer type instead then you could use 0, 1 and the other meaningful values but you could also use -42134 or 60000, neither of which correspond to any real result. the same goes for strings, where you might use "OK", "Cancel", etc. but you could also use "Hello World" and "Foobar".
Click Here to Expand Forum to Full Width