How to implement some constrained .NET struct/structure (let's say
LimitedString), where its state with default values (set by CLR to technical defaults, i.e. nulls, zeros, etc.) should be prohibited due to some design constraint?
For example in case of trivial
struct LimitedString, properties are
String Value and
int MaxLength = 10, where value of the
MaxLength property must be at least
0 is not allowed by design. But when I initalize the structure, I have
0 there. How to force value
10 into defaults?
I see two options:
- Throw exception in
shared) parameterless constructor → force using only costructor(s) with parameters. Impractical, parameterless use is expected sometimes.
- Add helper private field
IsInitializedand while it is
false, assume default values, i.e.
MaxLength = 10. Slightly higher complexity inside the struct.
Is option #2 a legitimate way or does this violate some design principles? Is there some better way than option #2?
EDIT: option #1 won't work anyway, mentioned constructor is called every time, even if other constructors are called.