C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
All About Constants
WhatsApp
Praveen Rai
6y
6
k
0
7
25
Blog
What are constants?
Constants are immutable values whose values are known at runtime and cannot be changed in the whole lifetime of a program.
Features of constants
Only C# primitive can be declared as const. Shown below is how a constant is declared.
User-defined Types such as class, struct and arrays cannot be declared as const.
A constant can only be initialized when it is declared and cannot be changed.
// Value assigned during compile time
class
A {
public
const
int
month = 12;
//Legal
}
// Value assingement during runtime
class
B {
public
const
int
month;
public
B() {
this
.month = 12;
// illegal
}
}
When the compiler encounters a constant identifier in C# code, it substitutes the literal value directly into the IL code that produces it because there is no variable address associated with the constant at runtime.
People also reading
Membership not found