Resharper possible null reference warning
Resharper gives a possible n开发者_StackOverflowull reference warning for the as cast here. Is there any possibility of it actually happening, or does the is check in the if statement preclude it?
IMyObjectType someObject = null; //MyObjectType implements IMyObjectType
if (someObject is MyObjectType)
{
(someObject as MyObjectType).SomePropery = true;
}
Edit: Whoops I was all wrong here - here is the right answer:
The is
operator checks for type compatibility and nullity so ReSharper should not warn in this particular case.
Proof:
using System;
class Example
{
static void Main()
{
Example example = null;
// this is always "false"
Console.WriteLine(example is Example);
}
}
More proof:
is (C# Reference):
An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
Old answer: This is incorrect but for the sake of completeness I will leave it here.
Yes, someObject
can still be null
here.
This only checks the type of the variable:
someObject is MyObjectType
The type of someObject
could very well be MyObjectType
but could point nowhere. In other words, there is a difference between the type of the reference and whether or not that reference points to an instance of an object.
Yes, the is
check precludes it.
As it turns out, your is check doesn't protect you from all cases. Consider the following:
MyObjectType obj = null;
ParentType someObject = obj;
In this case, the is
check will succeed but the value will still be null
.
Update
I was curious when I wrote the example above if I was correct or not. It turns out that I was not. The is check above will always return false (because the actual value is null).
You could make this a little cleaner and remove the warning by changing your code to:
var castObject = someObject as MyObjectType;
if(castObject != null)
castObject.SomeProperty = true;
I don't think ReSharper will be that smart. But in any event what I commonly see is something along the lines of
MyObjectType someTypedObject = someObject as MyObjectType;
if (someTypedObject != null)
{
// use the object
}
I was also a bit curious about this, but I can see that you pretty much already have answered the question.
However, since I made this nice image for you, I might as well upload it:
精彩评论