# const vs readonly in c#
Constant:- The Constant refer to fix values that the program may not alter during its execution.These fixed values are also called literals.
Example:-
class Program
{
const double pi = 3.14159; // Can be Used as field
const double
pi; //
Error- Initialization must, outherwise compilation error occur
public void Print()
{
const double pi = 3.14159; //:- Can be Used as a local variable
Console.WriteLine("value of PI: " + pi);
}
static void Main(string[] args)
{
Program obj = new Program();
obj.Print();
}
}
- Integer Constant
- Float Constant
- Character Constant
- String Constant
- Enumeration Constant
readonly string first_Name = "John"; // Can not be used as a local variable
class Age
{
private readonly int _year;
Age(int year)
{
_year = year;
}
public static void Main()
{
Age obj = new Age(2022);
Console.WriteLine("Age=" +obj._year);
}
}
We can assign a value to a readonly
field only in the following contexts:-
When the variable is initialized in the declaration.
In an instance constructor of the class that contains the instance field declaration.
In the static constructor of the class that contains the static field declaration.
No comments:
Post a Comment