Couldn't you just do
if ((TypeA SpecializedVariableA as MagicVariable) != null){
...
}
or something like that?
Couldn't you just do
if ((TypeA SpecializedVariableA as MagicVariable) != null){
...
}
or something like that?
I'd side with StyleCop.
Like it says, the first option performs the cast twice (the is
keyword has to try to cast and then find the new type) which is less efficient.
The second option only tries the cast once and is still very easy to read and understand.
If you're really worried about casting every time, you could try nested if
s:
TypeA specializedA = yourObject as TypeA;
if(specializedA != null)
{
// Do some work
}
else
{
TypeB specializedB = yourObject as TypeB;
if(specializedB != null)
{
// Do some work
}
}
But don't try to optimize before you find out that the code is performing poorly.
Elegance - i.e. readability - trumps performance in 95% of cases. Secondly the difference in speed here is going to be minimal. So pick the alternative that reads best and to hell with stylecop.
This is a previous discussion whose answer is applies to your question as well I think:
http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr
The first seems more efficient, since it will stop casting things as soon as it find a match - just order your if/else clauses with the most common ones at the top (if possible).
it just seems more 'correct' to me too.
I think it's one of those static code optmizations that will not give you any real world performance penefits. Sure the first option calls is
and explicit cast, but the second calls as
and a comparison. I reckon if you do it 5 billion times you would see very slim differences, in real world - 99.9999% gurantee it's not going to benefit performance at all.
As with any static code analysis, take it with a grain of salt. The puropse of the warning is to give you heads up that something might be inefficient. In this example I would say it's sagfe to ignore it
you can't even search for it on SO or anywhere else
Admittedly, it’s not easy. But how about Google site search: "is vs as"?
I find the first version more readable and clear. The statement in the if
expression actually states what is being checked.
While the second version may be more efficient, it isn't as clear, especially if the as
statement is separated from the if
statement by a few lines.
I doubt the performance gains realized by the optimized version will have any meaningful impact on your program's execution unless they occur in a very tight loop.