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?
[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:
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.