1.

What Are Constants In C#?

Answer»

Constants in C# are immutable values which are known at compile time and do not CHANGE for the life of the program. Constants are declared using the CONST keyword. Constants must be initialized as they are declared. You cannot assign a value to a CONSTANT after it isdeclared. An example is shown below.

using System;
CLASS Circle
{
PUBLIC const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below.

using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}



Discussion

No Comment Found