Validation for primary constructors

Topics: C# Language Design
Apr 11, 2014 at 3:09 PM
Edited Apr 11, 2014 at 3:24 PM
Primary constructors were a great addition to the language but the fact is it's kinda ugly how validation is performed (so far I'm doing it with validation methods, one for property, scattered all over the class).

I'd like to propose something similar to Java Initialization blocks. That block of code would be added to the constructor that is generated because of primary constructor feature. Something along these lines:

public class SuperDuperClass(int a, string b)
//This block of code would be added to the primary constructor
if (a < 0) throw new Exception("...");
if (b == null) throw new Exception("...");


Once all constructors must have to call the primary constructor those validations would run no matter which constructor gets called on the client site.

I'm not sure whether or not that should be allowed if a primary constructor is not defined.

How about that?