Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Practical Difference Between Constant And Readonly In C#
WhatsApp
sushil kumar
8y
5.1
k
0
6
25
Blog
Constant(const)
Readonly
Constants are immutable values and do not change their value for the life of the program.
Constants are known as the compile time.
ReadOnly is also an immutable value and does not change its value for the life of the program.
ReadOnly is known as the runtime.
Assigned a value at the time of declaration.
Ex
public
const
int
number = 0;
Assigned a value either at the run time or inside a constructor (instance initialization).
Ex
class
Program {
public
readonly
int
number = 10;
public
Program() {
number = 20;
}
}
Constant cannot be static i.e. you cannot declare constant as static.
Ex
public
static
const
int
number = 10;
It will throw an error at the compile time.
Readonly can be static i.e. you can declare readonly as static.
Ex
public
static
readonly
int
number = 10;
It will not give an error.
Constant value can access with the class name.
Ex
class
Program {
public
const
int
number = 10;
static
void
Main() {
Console.Write(Program.number);
}
}
Readonly value can access by instance of the class.
Ex
class
Program {
public
readonly
int
number = 10;
static
void
Main() {
Program p =
new
Program();
Console.Write(p.number);
}
}
Constant In C#
Readonly In C#
C#
Up Next
Difference Between Constant And ReadOnly
Ebook Download
View all
Programming C# for Beginners
Read by 149.2k people
Download Now!
Learn
View all
Membership not found