Joan Venge
Joan Venge

Reputation: 331450

Contracts in C# 4.0

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?

Upvotes: 2

Views: 1599

Answers (2)

Daniel Earwicker
Daniel Earwicker

Reputation: 116744

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.

Upvotes: 3

Scott Dorman
Scott Dorman

Reputation: 42526

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.

Upvotes: 1

Related Questions