0

I have a private execute method ClickExecute for a Command object Command. I am binding a parameter object which is of type TypeA. It has a property IsValid which I want to check in code contract as shown below.

ClickCommand = new DelegatingCommand(ClickExecute);

private void ClickExecute(object parameter)
    {
        var typeA= parameter as TypeA;
        Contract.Requires<ArgumentNullException>(typeA!= null, "typeA");
        Contract.Requires<ArgumentException>(typeA.IsValid, "Not Valid");
    }

When I do this I get the compile error - error CC1025: After contract block, found use of local variable 'typeA' defined in contract block

What am I doing wrong? I need to do a type cast before I check

[Edit]

Matthew's answer is helpful and resolved the CodeContract issue which is -

        Contract.Requires<ArgumentNullException>(parameter is TypeA);
        Contract.Requires<ArgumentException>((parameter as TypeA).IsValid);
        var typeA = parameter as TypeA;

But this introduces new problem of repetitive type casting with this approach and causes the Static Code analysis error -

CA1800 : Microsoft.Performance : 'parameter', a parameter, is cast to type 'TypeA' multiple times in method

Is there a cleaner way to avoid this?

Carbine
  • 7,849
  • 4
  • 30
  • 54

1 Answers1

2

[EDIT] Changed to accommodate the edits to the OP

You must put all the requires BEFORE any other code.

So you will have to rewrite the code like so:

private void ClickExecute(object parameter)
{
    Contract.Requires<ArgumentException>(parameter is TypeA);
    Contract.Requires<ArgumentException>(((typeA)parameter).IsValid);
}

Note that I also changed things around slightly - you don't really need to specify strings for the error message; it's better to let it output the actual failing check code, which it does by default.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Apologies for the error, the second contract should be TypeA.IsValid – Carbine Dec 16 '13 at 10:25
  • Thanks Matthew that was very useful and solved the Codecontract problem. From your answer I prefer - `Contract.Requires((parameter as typeA).IsValid);` than explicit type casting. Old habits :) – Carbine Dec 16 '13 at 10:39
  • @Bharath Well, the explicit cast shows that you are expecting the value to be of that type (and it will throw an exception if it is not) whereas using `as` indicates that you only *think* it will be of that type, and should always be followed by a check against null, which you are not doing. Hence, it is better to use the explicit type cast in this scenario. – Matthew Watson Dec 16 '13 at 11:31
  • You are correct, but the contact to check the type using 'is' would have caught this was my assumption. Hence I felt to ignore explicit cast. – Carbine Dec 16 '13 at 11:38