Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# class and readonly members

Tags:

c#

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?

like image 275
Bobbo Avatar asked Jan 07 '11 16:01

Bobbo


2 Answers

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.

like image 112
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet


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.

like image 34
Adam Robinson Avatar answered Oct 12 '22 23:10

Adam Robinson