开发者

C# class and readonly members

When writing a class in C#, is it a good idea to mark all of you private member variables as private readonly if the开发者_如何学Cy are only assigned to in the constructor and aren't subject to change elsewhere in your class? Or is this overkill?


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.


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.


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;}}


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜