Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Contracts Vs. Object Initializers (.net 4.0)

At face value, it would seem that object initializers present a problem for .net 4.0 "code contracts", where normally the invariant should be established by the time the object constructor is finished. Presumably, however, object-initializers require properties to be set after construction is complete.

My question is if the invariants of "code contracts" are able to handle object initializers, "as if" the properties were set before the constructor completes? That would be very nice indeed!!

like image 365
Brent Arias Avatar asked May 02 '10 07:05

Brent Arias


1 Answers

Well, I suppose Code Contracts could insert an extra call to an invariant at the end of the object initializer - if it could tell that that was being used. (Don't forget that it mostly uses the IL rather than the source code; as far as I'm aware, the source code is only used to generate error messages.)

This strikes me as poor design though - encouraged by the unfortunate nature of object initializers. What would you do about setting properties after the object initializer? They could make the object invalid again.

It sounds like you basically want at least some properties to be immutable, but you want the benefit of the simplicity of object initializers. Named arguments and optional parameters in C# 4 give you some of this - create a constructor with all the appropriate properties (and default values) then you can call it like this:

Person person = new Person(firstName: "Jon", lastName: "Skeet");

This isn't far off the object initializer syntax:

Person person = new Person { FirstName = "Jon", LastName = "Skeet" };

It's not ideal, and I wish C# had more support for immutable types (both creating and using), but it's a start...

like image 174
Jon Skeet Avatar answered Oct 03 '22 18:10

Jon Skeet