I am trying to resolve some fxcop issues and I am really confused about this issue.
In a setter of a derived class, I am checking if assignment should be made
if (!(value is TypeA))
{
throw new ArgumentException("value is not of TypeA type");
}
_action = (TypeA)value;
FxCop is complaining:
‘value’, a parameter, is cast to type ‘TypeA’ multiple times in method. Cache the result of the ‘as’ operator or direct cast in order to eliminate the redundant castclass instruction.
BUT, in this msdn example (is definition ) I see this:
if (o is Class1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
}
which is exactly the same thing I do. So, is there a resolution for this?
All I can think is:
TypeA tmpAction = value as TypeA;
if(tmpAction == null)
{
throw new ArgumentException();
}
_action = tmpAction;
The example you give is correct – if you need to cast and use a variable with the type you cast to, use
asand anullcheck instead ofisso you don’t have to do it twice.