Variables are great for storing values, but sometimes you don't want a value to change, and as in C++, you can make such values into constants. Declaring a constant works just as declaring a variable, except that you also use the const keyword:

 [  attributes  ] [  modifiers  ] const  type declarators  ; 

The parts of this statement are just the same as for variables; in fact, declaring a constant is like declaring a variable, but you just use the const keyword. Take a look at ch01_03.cs in Listing 1.3, where we're declaring a constant named pi and displaying its value.

Listing 1.3 Using a Constant (ch01_03.cs)
 class ch01_03 {   static void Main()   {     const float pi = 3.14159f;     System.Console.WriteLine("Pi = {0}", pi);   } } 

Here's what you see when you run this code:

 C:\>ch01_03 Pi = 3.14159 

If you try to assign a new value to our constant named pi , your code won't compile. Here's an example, where we're trying to change the value of pi :

 class ch01_03 {   static void Main()   {     const float pi = 3.14159f;  pi = 3.14f;  System.Console.WriteLine("Pi = {0}", pi);   } } 

Here's the error message you get when you try to compile:

 ch01_03.cs(6,9): error CS0131: The left-hand side of an assignment must be a     variable, property or indexer 

Microsoft Visual C#. NET 2003 Kick Start
Microsoft Visual C#.NET 2003 Kick Start
ISBN: 0672325470
EAN: 2147483647
Year: 2002
Pages: 181

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: