zerocewl
zerocewl

Reputation: 12804

How to use 'readonly' as member keyword in C# 8.0?

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.

Upvotes: 2

Views: 2048

Answers (2)

Nicklaus Brain
Nicklaus Brain

Reputation: 929

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.

Upvotes: 4

user12031933
user12031933

Reputation:

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.

Upvotes: 1

Related Questions