The C# “readonly” keyword is a modifier that when a field declaration includes it, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
Now suppose I do want this “assign value once” constraint, but I would rather allow the assignment be done outside of constructors, a lazy/late evaluation/initialization maybe.
How could I do that? and is it possible to do it in a nice way, for example, is it possible to write some attribute to describe this?
Note that lazy initialization is complicated, so for all of these answers you should be careful if you have multiple threads trying to access your object.
If you want to do this inside the class
You can use the C# 4.0 built-in lazy initialization features:
Or for older versions of C#, just supply a
getmethod, and check if you’re already initialized by using a backing field:If you want to do this outside the class
You want Popsicle Immutability:
Basically:
Freezemethod.ModifyFrozenObjectException.IsFrozen.BTW, I made up these names just now. My selections are admittedly poor, but there is no generically followed convention for this yet.
For now I’d recommend you create an
IFreezableinterface, and possibly related exceptions, so you don’t have to depend on the WPF implementation. Something like: