I come from a C++ background and am trying to become proficient in C#. It seems like C# always has 2 types of modifiers wherever C++ had one. For example, in C++ there is &
for references and then in C# there is ref
and out
and I have to learn the subtle differences between them. Same with readonly
and const
, which are the topic of this thread. Can someone explain to me what the subtle differences are between the 2? Maybe show me a situation where I accidentally use the wrong one and my code breaks.
Asked
Active
Viewed 365 times
-3

Subpar Web Dev
- 3,210
- 7
- 21
- 35
-
3would you mind search in google? http://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly – M.kazem Akhgary Mar 04 '16 at 17:21
-
Or try searching here. Closing for duplicate. – crashmstr Mar 04 '16 at 17:22
-
@M.kazemAkhgary My question is more about why their exist 2 such modifiers in the first place. My enthusiasm for learning C# is going to drop unless I'm convinced that the language features are necessary. – Subpar Web Dev Mar 04 '16 at 17:22
-
3I suspect you'll get more mileage from learning C++. Find out why `const_cast<>` is provided by the language. And why it had to add the `mutable` keyword later. All hacks around the not-so-great *const* keyword, hacks that the C# designers were well aware of. – Hans Passant Mar 04 '16 at 17:28
-
1You probably should stop learning C# then... There are a lot of things that are not strictly necessary - like `?:` and `??` when simple `if` is enough, multiple ways to represent delegates,.. Note that while asking for "why feature X is designed in language in particular way" are on-topic such post should show reasonable understanding/research about feature to stay on its own. In current state of the question it clear duplicate due to just asking about differences. – Alexei Levenkov Mar 04 '16 at 17:31
-
http://stackoverflow.com/questions/441420/why-does-c-sharp-limit-the-set-of-types-that-can-be-declared-as-const – M.kazem Akhgary Mar 04 '16 at 17:36
1 Answers
0
Readonly: Can only be set in the constructor.
Const: Is a COMPILE TIME CONSTANT. I.e. can not be determined at runtime.

TomTom
- 61,059
- 10
- 88
- 148