tags:

views:

1009

answers:

2

If I have a Vector3.Normalize() method that specifies a post condition where the resultant Vector3 is gonna have a length of 1, how would the compiler check for this at compile time (or before)? Does it just pass a random Vector3 variable to the method?

+1  A: 

I'm pretty sure the code contracts stuff in C# 4.0 will happen at runtime, not compile time, and that you would need to actually specify the condition in the call. Supposing your Vector3 class has a Length property, you would end up with something like this:

Expects(vector3.Length == 1);

Which would actually hit some IL rewriting during a sort of post-compilation step which would end up essentially wrapping the body of the method in a try..finally where the post condition test is in the finally block.

Scott Dorman
Some of the statically-verifiable contracts will be compile-time checked, but situations like this will be checked at runtime as you say.
Erik Forbes
+3  A: 

This isn't a feature of C# 4.0. It's a language-independent feature of CLR 4.0 that works at the IL level. It does have some ability to perform static checking, but not for every kind of condition. It actually analyzes the IL generated by the normal compiler for whatever language you're using, finds the constraints you put in the code and then looks at the code to figure out if it is going to meet the contract. The static checking (at least in demos I've seen) is an optional feature.

Daniel Earwicker
Thanks, so does that mean C# might not have the Spec# syntax for it? Like Linq is a library but C# 3.0 has some Linq keywords built-in. Could it be the same with C# 4.0+ by adopting Spec# style contract usage?
Joan Venge
According to the PDC announcements, C# 4.0 will definitely not have the Spec# syntax. 'Code Contracts' is a purely CLR-level, language independent feature. This fits into Microsoft's general strategy now of ensuring most capabilities are available across all languages.
Daniel Earwicker