views:

237

answers:

1

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!!

+6  A: 

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...

Jon Skeet
I agree, more support for immutable types in C# would be great.
Steven
Hip Hip Hooray for named arguments and optional parameters! Two of the small handful of VB features I have missed since jumping ship.
Sky Sanders
@Jon: Actually "setting properties after the object initializer" does not alarm me - since the client is responsible for not breaking the precondition associated with each property. I just want to avoid the a situation where I practically cannot supply an invariant, because object initializers and code contracts don't get along. It sounds like the jury is out on object initialers though, as you say "code contracts *could* make a call to an invariant when object initializers complete." But it does seem more likely that optional / default params will play well with code contracts
Brent Arias