Reputation: 1813
When writing a class in C#, is it a good idea to mark all of you private member variables as private readonly if they are only assigned to in the constructor and aren't subject to change elsewhere in your class? Or is this overkill?
Upvotes: 8
Views: 4264
Reputation: 286
Readonly makes very much sense in situations where you pass a service reference through constructor, i.e.
public class MyViewModel
{
private readonly MyContext context;
public MyViewModel(MyContext context)
{
this.context = context;
}
}
You obviously don't want your context overwritten with another one, because you can have a lot of stuff dependent on that particular service inside the class. And if it's a constructor parameter, that usually means you RELY on that particular service or object for creating and keeping the valid state of the object. So readonly is a good indicator of just that. Having private set on property means that you can't change it outside the class, readonly is an extra constraint which makes things a bit more secure and understandable.
Upvotes: 0
Reputation: 67345
If I'm 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
Upvotes: -1
Reputation: 904
Wow what a good question and one that is purely going to be answered with opinions. My opinion is I always just create properties to the variable. An example is as follows.
private int _myInt;
private int myInt {get{return _myInt;}}
Upvotes: 1
Reputation: 46018
Yes - you won't run into problems with their values being modified later on by some code written by other developer that didn't know that they should be read-only.
Upvotes: 0
Reputation: 185703
Yes, that is what readonly
specifically indicates. If you already know (or can at least assume) that you're not going to assign it anywhere else, then marking it readonly
is a good idea. After all, it's easier to remove readonly
than it is to add it later.
Upvotes: 4
Reputation: 1503489
Yes, personally I believe it's a good idea. I try to keep types immutable where possible, and declaring a variable readonly
is a good start to that. It's not the be-all and end-all, of course - if that variable is something mutable (e.g. a StringBuilder
or an array) then it's really not helping all that much. I'd still make the variable read-only though to make it obvious that I don't want to change the value of the variable itself - and to prevent myself from doing so accidentally elsewhere in the same class, possibly months or years later.
Upvotes: 11