C # class and read-only members

When writing a class in C #, is it recommended to mark all private member variables as private readonly if they are assigned only in the constructor and cannot be changed elsewhere in your class? Or is it too much?

+8
c #
source share
6 answers

Yes, personally, I consider this a good idea. I try to keep types unchanged where possible, and declaring a readonly variable is a good start to this. Of course, this is not all-all and all-finite - if this variable is something mutable (for example, a StringBuilder or an array), then this really does not help much. Anyway, I’ll make the variable read-only, but I’ll make it obvious that I don’t want to change the value of the variable itself - and do not allow myself to do it by accident in another place of the same class, perhaps months or years later.

+10
source share

Yes, that is what readonly points out. If you already know (or at least assume) that you are not going to assign it elsewhere, then its readonly labeling is a good idea. In the end, it’s easier to remove readonly than add it later.

+4
source share

Wow, a good question and one that only opinions will answer. My opinion is that I always create properties for a variable. An example is as follows.

 private int _myInt; private int myInt {get{return _myInt;}} 
+1
source share

Yes - you will not encounter problems when their values ​​are changed later by some code written by another developer who did not know that they should be read-only.

0
source share

Readonly makes a lot of sense in situations where you pass a link to a service through a constructor, i.e.

public class MyViewModel { private readonly MyContext context; public MyViewModel(MyContext context) { this.context = context; } }

Obviously, you do not want your context to be overwritten by others, because you can have many things that depend on this particular service inside the class. And if this is a constructor parameter, it usually means that you are RELY on this particular service or object to create and maintain the actual state of the object. So readonly is a good indicator of just that. Having a private set in a property means that you cannot change it outside the class; readonly is an additional restriction that makes things more secure and understandable.

0
source share

If I am only going to initialize a variable once and never write to it, I would make it const.

http://en.csharp-online.net/const,_static_and_readonly

-one
source share

Source: https://habr.com/ru/post/650802/


All Articles