Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the result of as operator be null if the is operator returns true?

Tags:

c#

casting

I am using code quality tools and they are saying that I can have a null deference on line 3 in the following block style:

1    if(var1 is Type1)
2    {
3         (var1 as Type1).methodCall();
4    }

It sugests making the following change:

1    Type1 tempVar = var1 as Type1; 
2    if(tempVar != null)
3    {
4         tempVar.methodCall();
5    }

How does this change the potential for a null deference exception? According to msdn is will return true if "provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown." (http://msdn.microsoft.com/en-us/library/scekt9xw.aspx)

What senerio is there where var1 is Type1 would evaluate to True, but var1 as Type1 evaluates to null. Or is this not possible and just a limitation of the code quality tools.

I am using jetbrains re-sharper and hp fortify.

like image 806
Zac Avatar asked Nov 17 '14 19:11

Zac


2 Answers

The only way that your first program could throw a NRE is if var1 could potentially be mutated from another thread after the check and before the method invocation. Assuming that you don't need to be concerted about mutation from another thread (or already have proper synchronization in place) this is a false positive of the code analysis tool and your original code won't throw a NRE.

like image 175
Servy Avatar answered Nov 28 '22 10:11

Servy


The value of var1 could change between the is and as if another thread can access it.

Even if it's unlikely, or even impossible in your specific situation, the suggested code is completely immune against such changes, so it's good practice.

The suggested code also does the type check only once, so it even performs slightly better. Even if the performance difference is not always significant, it still means that you get better code at no extra cost.

like image 36
Guffa Avatar answered Nov 28 '22 08:11

Guffa