-3

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.

6
  • 3
    would you mind search in google? stackoverflow.com/questions/55984/… Mar 4, 2016 at 17:21
  • Or try searching here. Closing for duplicate.
    – crashmstr
    Mar 4, 2016 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. Mar 4, 2016 at 17:22
  • 3
    I 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. Mar 4, 2016 at 17:28
  • 1
    You 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. Mar 4, 2016 at 17:31

1 Answer 1

0

Readonly: Can only be set in the constructor.

Const: Is a COMPILE TIME CONSTANT. I.e. can not be determined at runtime.

Not the answer you're looking for? Browse other questions tagged or ask your own question.