1

I like to know the correct way to use the readonly keyword for members introduced with C# 8.0 in difference to the 'const' keyword.

zerocewl
  • 11,401
  • 6
  • 27
  • 53

2 Answers2

4

I would say that correct ways are precisely described by official proposal. But to make a general comment I will add, that this readonly keyword for struct, does not really make functional changes to your existing code (except compiler warnings when readonly marked method tries to change the struct state). This new syntax, is infact a kind of indicator for compiler that allows it better code optimization by not generating extra copies of the value types. It has nothing in common with const keyword, because const is only applicable for constants of the basic types (like int or string) (See https://exceptionnotfound.net/const-vs-static-vs-readonly-in-c-sharp-applications/ & Static readonly vs const on the question.

Nicklaus Brain
  • 884
  • 6
  • 15
1

Readonly exists since the beginning of C#.

Const is used to declare a constant value that is interpreted by the compilator as a raw value that is not an instantiated variable. It can not be an instance, it is a immutable value.
https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/const

Readonly is used to declare an instance that can't be re-assigned. It is an instance variable that can't be changed.
https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/readonly

For example, you can write:

const string MyString = "A string";
const int MyInteger = 10;

But you can't write:

const Form Instance = new Form();

You must use:

readonly Form Instance = new Form();

Readonly members can be assigned in a constructor.

  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/readonly-instance-members – zerocewl Sep 23 '19 at 19:12
  • Ok, thanks for the information about the new usage of this keyword. So the OP question has nothing to do about the const keyword? I found this usage a little confusing, hence the question of OP. Another keyword should have been introduced for that usage, like "unmutate". –  Sep 23 '19 at 19:21
  • @OlivierRogier Be careful what you wish for, or they'll decide to use `const`, and you'll get articles about const correctness, C# style. – Ray Sep 23 '19 at 19:57
  • @Ray I did not understand what you are saying. What wish? What correctness? What C# style? They? Const may be used in some cases for optimization... –  Sep 23 '19 at 20:10
  • @OlivierRogier Don't worry, it's just a pun on some people not being able to understand the many ways of applying the similar `const` keyword in C++. – Ray Sep 23 '19 at 20:11
  • @Ray I am not good enough in English that is not my native language :) –  Sep 23 '19 at 20:13