You can avoid the use of privilege initializers and simply move all this code to the constructor using optional parameters if there are many properties. This way you get the property initializer constructor and still be able to check the class after initialization is complete. Something like that:
class Foo { public string Foo {get; set;} public string Bar {get; set;} public bool IsValid {get ; set;} private void Validation() { if(foo == "") IsValid = false; if ... } public void Foo(string foo = string.Empty, string bar = string.Empty) { Foo = foo; Bar = bar; Validation(); } } ..... var t = new Foo (Foo = "SomeString");
The downside is that it is a relatively new C # 4 syntax.
If you cannot use C # 4, you can use property accessors to enable validation, for example. as:
public string Foo { get { return foo; } set { foo = value; Validation(); } }
but this will evaluate the validity for each set and can be slow if you set a lot of properties right away. You can also use the get accessory in combination with some lazy loading, something like this:
public bool IsValid { get { if (!isValidated) Validation(); return isValid; } private set { isValid = value; } } public string Foo { get { return foo; } set { foo = value; isValidated := false; } }
Sweko source share