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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With