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

I use code quality tools, and they say that I can have zero reverence in line 3 in the following block style:

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

This leads to the following changes:

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

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

What is senerio, where var1 is Type1 will evaluate to True, but var1 as Type1 evaluate to null. Or is it impossible and just a limitation of code quality tools.

I use reactive brains with repetition and amplification of hp.

+5
source share
2 answers

The only way your first program can generate NRE is if var1 can be changed from another thread after checking and before calling the method. Assuming you don’t need to match the mutation with another thread (or you already have the appropriate synchronization), this is a false result of code analysis and your source code will not generate NRE.

+10
source

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

Even if this is unlikely or even impossible in your specific situation, the proposed code is completely protected from such changes, so this is good practice.

The proposed code also checks the type only once, so it even works a little better. Even if the difference in performance is not always significant, it still means that you get the best code at no additional cost.

+1
source

Source: https://habr.com/ru/post/1207067/


All Articles