I'm sure I've seen somewhere that I can do the following by using an attribute above my Init() method, that tells the compiler that the Init() method must only be called from the constructor, thus allowing the readonly field to be set. I forgot what the attribute is called though, and I can't seem to find it on google.
public class Class { private readonly int readonlyField; public Class() { Init(); } // Attribute here that tells the compiler that this method must be called only from a constructor private void Init() { readonlyField = 1; } }
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
You can use readonly to set the read-only attribute for the variables specified by name. A variable with the read-only attribute cannot have its value changed by a subsequent assignment and cannot be unset. Note that qsh can change the value of a variable with the read-only attribute.
A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.
Rob's answer is the way to do it, in my book. If you need to initialize multiple fields you can do it using out
parameters:
public class Class { private readonly int readonlyField1; private readonly int readonlyField2; public Class() { Init(out readonlyField1, out readonlyField2); } protected virtual void Init(out int field1, out int field2) { field1 = 1; field2 = 2; } }
Personally I find this makes sense in certain scenarios, such as when you want your fields to be readonly
but you also want to be able to set them differently in a derived class (without having to chain a ton of parameters through some protected
constructor). But maybe that's just me.
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