Changes

Jump to: navigation, search

C Sharp Variables and Constants

42 bytes added, 16:28, 14 January 2008
What is a C# Constant?
== What is a C# Constant? ==
A constant is similar to a variable in that it provides a named location in memory to store a data value. Constants differ in one significant way in that once a value has been assigned to a constant it cannot subsequently be changed.
Constants are particularly useful if there is a value which is used repeatedly throughout the application code. Rather than use the value each time, it makes the code easier to read if the value is first assigned to a constant and which is then referenced in the code. For example, it might not be clear to someone reading your C# code why you used the value 5 in an expression. If, instead of the value 5, you use a constant named ''interestRate'' the purpose of the value becomes much clearer. Constants also have the advantage that the if the programmer needs to change a widely used value it only needs to be changed once in the constant declaration and not each time it is referenced.
As with variables, constants have a type, a name and a value. Unlike variables, constants must be initialized at the same time that they are declared and must be prefixed with the ''const'' keyword:
</pre>
Note that a constant, unlike a variable, must be initialized at the point that it is declared. For example, the follwoing following code:
<pre>
</pre>
will result in a compilation error along the lines of ''A const field requires a value to be provided''. Now that we have described C# variable variables and constants it is time to start looking at the different ''types''that are available to us as C# programmers.
== C# Integer Variable Types ==

Navigation menu