[edit] The C# const keyword
The constant keyword makes a variable unchangable. PI = 3.14 it does not need to change. Constants cannot be placed on the left side of the expression, otherwise the compiler will issue errors when you attempt to compile your program. A const MUST be initialized with a value when it is declared.
[edit] Advantages of the C# const
- Very good performance benefits
- Good programming practice
[edit] Example 1:
This example will compute the area of a circle
using System;
class Program
{
static void Main()
{
const float PI = 3.14f;
float radius = 1.5f;
Console.WriteLine(PI * radius * radius);
Console.Read();
}
}
Output:
7.065
[edit] Example 2:
This program will attempt to add two numbers.
using System;
class Program
{
static void Main()
{
int number1 = 8;
int number2 = 3;
const int result = 0;
result = number1 + number2; //ERROR--const can't be on left side
Console.WriteLine(result);
Console.Read();
}
}
Notice: This code will not compile because the const variable is on the left side
|