What is the difference between keywords const and readonly in C#?
Const
Constant fields are the fields that cannot be modified. At the time of declaration, you need to assign a value to it.
const int a = 5;
Readonly
A Read-only field is initialized at the time of declaration or you can also set it within the constructor.
Let us see an example in which the read-only field is initialized inside the constructor −
Example
class Calculate {
readonly int z;
public Demo( ) {
z = 20;
}
}
Published on 16-Aug-2018 11:26:22
- Related Questions & Answers
- Explain the difference between const and readonly keywords in C#
- Difference between readonly and const keyword in C#
- What is the difference between const int*, const int * const, and int const *?
- What is the difference between #define and const Keyword in C++?
- What is the difference between VAR and DYNAMIC keywords in C#?
- Difference between const int*, const int * const, and int const * in C/C++?
- Difference between const int*, const int * const, and int const * in C
- What is the difference between public, static and void keywords in C#?
- What is difference between int and const int& in C/C++?
- What is the main difference between Object.freeze() and const in JavaScript?
- What is the difference between super and this, keywords in Java?
- What is the difference between keywords and reserved words in Java?
- What is the difference between throw and throws keywords in Java?
- Difference between #define and const in C
- Difference between const char* p, char * const p, and const char * const p in C