Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a newbie. I have read in many blogs that const keyword can only be used with primitive types in C# but why? What is the reason behind this limitation?

What I have tried:

I have searched this query in Google but haven't find any reasonable answer to this
Posted
Updated 5-May-22 10:08am

Because const are not variables. Even though they are named, they are really just a compile-time replacement of a value wherever it's used.

Reference types specified as const can only be null. They cannot have an instance. An instance cannot be const because any variable in it can be changed at runtime without impacting the parent at all, hence, there's no way to make it constant.
 
Share this answer
 
Comments
OriginalGriff 5-May-22 16:09pm    
:thumbsup:
As Dave says, const values are constants, and only primitive types can be expressed as a constant literal at compile time.
However, there is readonly which is the struct / class equivelant - a value that can only be set in an instance constructor or as part of the declaration: readonly keyword - C# Reference | Microsoft Docs[^]
However, a readonly reference type is not immutable (unlike a const or a readonly struct which is). The reference variable can't be changed, but the values in the reference object instance can.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900