1

Can I use System.Reflection classes and methods in Code Contracts construction, that would check during static analysis? I want to define contract like that:

[ContractInvariantMethod]
private void ObjectInvariant()
{
    Contract.Invariant(GetType().GetMethods().Any(x => x.Name == "Add"),"Error");
}

When I run application, this condition is checked. But it isn't checked during compilation. May I somehow enable static checks for contracts like that?

mao
  • 1,364
  • 3
  • 14
  • 26

3 Answers3

2

I am not aware of any technical limitations but this is not the best solution. Code contracts are for checking run time state or changes, not (effectively) immutable things like the methods on a type.

Instead, I would either create a unit test that checks for the method or create a rule in a static analysis tool like FXCop.

akton
  • 14,148
  • 3
  • 43
  • 47
  • Thanks.Can I define a rule like that: "If MyClass derive from SomeBaseClass, it should contain field Field1 of type MyClass" using FxCop? – mao Sep 04 '12 at 03:03
  • It is possible with FXCop but it is probably overkill for the example in the question. If you want to require a method or property is present, use an interface as Steven says in his answer. If you want to ensure a method is not present, like in your question, an automated unit test using reflection is the easiest solution. – akton Sep 04 '12 at 03:05
  • I 100% agree. Code Analysis examines the binary code. This is not a contract of a class instance, but a binary (code analysis) *rule* on your class' implementation. – myermian Sep 04 '12 at 03:17
0

Code Contracts is not meant to fix design flaws. Your class should implement an interface that contains an Add method.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • Thanks, but assume that I can't change code of class that way (like implementing interfaces or inheriting from abstract classes). – mao Sep 04 '12 at 03:05
  • If you can implement an `ObjectInvariant` method on that type, you can implement an interface. Otherwise, write a unit test. This is the best thing after compile time checking. – Steven Sep 04 '12 at 03:14
0

The following is quite and old post, but it seems to be valid still. It says "the static checker does not use reflection to validate contracts".

Tamas
  • 6,260
  • 19
  • 30