Constants in C#
Notes:
Constants in C# Programming Language:
Variable:
Variable is a named memory location, whose value can change during the execution of a program.
Constant:
Constant is a named memory location, whose value never changes during the execution of a program once it is initialized.
There are 2 types of constants in C#:
1. Compile time constant
- is created using const keyword
2. Run time constant
- is created using readonly keyword
Compile time constant:
- is created using const keyword
- must and should be initialized when it is declared
Syntax for declaring and initializing a constant using const keyword:
const datatype NAME_OF_CONSTANT = ivalue;
Ex:
const float PI = 3.142f;
const float E = 2.71828f;
Syntax for declaring and initializing multiple constants using const keyword:
const datatype NAME_OF_CONSTANT1 =ivalue, NAME_OF_CONSTANT2 =ivalue,...;
Ex:
const float PI = 3.142f, E = 2.71828f;
Run time constant:
- is created using readonly keyword
- can be initialized while declaring itself or later inside the constructor of a class at run time
- is also called readonly variable
- run time constant must be a field of a class
Syntax for declaring a constant using readonly keyword:
readonly datatype NAME_OF_CONSTANT;
Ex:
readonly float PI;
readonly float E;
Syntax for initialing a readonly constant:
NAME_OF_CONSTANT = ivalue;
Ex:
PI = 3.142f;
E = 2.71828f;
Syntax for declaring multiple constants using readonly keyword:
readonly datatype NAME_OF_CONSTANT1, NAME_OF_CONSTANT2,...;
Ex:
readonly float PI, E;
Syntax for declaring and initializing multiple constants using readonly keyword:
readonly datatype NAME_OF_CONSTANT1 =value, NAME_OF_CONSTANT2 =value,...;
Ex:
readonly float PI = 3.142f, E = 2.71828f;
Example Code:
using System;
namespace ConstantsDemo
{
class Program
{
//static readonly float PI;
//static readonly float E;
// static readonly float PI, E;
static readonly float PI = 3.142f, E = 2.71828f;
static Program()
{
//PI = 3.142f;
//E = 2.71828f;
}
static void Main(string[] args)
{
/*
int playerScore = 0;
Console.WriteLine("player score = " + playerScore); // 0
playerScore = 10;
Console.WriteLine("player score = " + playerScore); // 10
const float PI = 3.142f;
Console.WriteLine("PI = " + PI); // 3.142
// PI = 4.142f; // error
const float E = 2.71828f;
Console.WriteLine("E = " + E); // 2.71828
const float PI = 3.142f, E = 2.71828f;
Console.WriteLine("PI = " + PI); // 3.142
Console.WriteLine("E = " + E); // 2.71828
*/
Console.WriteLine("PI = " + PI); // 3.142
// PI = 4.142f; // error
Console.WriteLine("E = " + E); // 2.71828
// E = 3.71828f; // error
Console.ReadKey();
}
}
}