C# Tutorial - Application 10 – Working with ConstantsThere are times when you require the ability to define a variable that should never be reassigned. The keyword const when applied to a variable causes it to become fixed and unalterable. Once a variable is constant, any attempt to change it will result in a compile time error. So what variables can be constant? Any value type or string. If any other reference type was constant, it would have to be referenced to null because of the compile time nature of const. private const int ZERO = 0; public const double PI = 3.14159265; private const string PRODUCT_NAME = "Visual C# Express"; Although you can use any naming convention you like, I have always found it easier to capitalise constants, as they stand out in code, and therefore you do not try to modify them in code. An ExampleTo understand this better, create a new console Application called App10. We are going to create a simple application that asks what age you are and then tells you whether you can legally drink alcohol. But what age can you drink alcohol at? This is dependant upon the country that you are in. For this application, the code assumes that the legal age for consumption of alcohol is 18. The beauty of using a constant is that you can change the value of it in one place only and recompile the application to redeploy it in a country with a different age limit. First of all we need to modify our Person class, so that we implement the property for Age. class Person
{
// Attributes
private string _forename;
private string _surname;
private string _address;
private int _age;
private bool _gender;
private string _dateOfBirth;
private int _telephoneNumber;
private int _NINumber;
public Person()
{
}
public string ForeName
{
get { return _forename; }
set { _forename = value; }
}
public string SurName
{
get { return _surname; }
set { _surname = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
}
Now we create the application including our constant. class Program
{
static void Main(string[] args)
{
const int LEGAL_AGE = 18;
Person p = new Person();
Console.Write("What is your age? ");
p.Age = Convert.ToInt32(Console.ReadLine());
if (p.Age >= LEGAL_AGE)
Console.WriteLine("You are legal to drink alcohol");
else
Console.WriteLine("You are illegal to drink alcohol");
}
}
The code gives the following screen shots. ![]() Under Age to Drink
![]() Allowed to Drink
|