Basic of C# - Const and Readonly

The first difference we need to know about const and read-only.

Const variable in C#

Const variable is immutable and it is known when the program compilation is happening, and does not change the value for the lifetime of the program.

The read-only variable is also immutable, and it is known when the program is at runtime; it also does not change the value for the lifetime of the program.

When you declare a variable with a const keyword, it is immutable after declaration. and since const is known to program when it's compiling it is mandatory to give value to const. If you do not assign a value to a const variable it will give an error.

When you declare a constant variable with a value, it is a static value by default. When you declare a variable using a read-only keyword, it is also an immutable variable after initialization. This means it does not have to be declared at the time of compiling, they can be constructed under the constructor, which means we can only modify read-only variables inside the constructor.

If the class was created more than once, each time when the class is instantiating, the read-only also gets declared.

Ebook Download
View all
Learn
View all
GE HealthCare will never ask for payment to process documents, refer you to a third party to process