Alex
Alex

Reputation: 9429

PropertyInfo.GetValue returned object is not seen as null by visual studio / resharper

I'm retrieving the value of a property by calling the GetValue like so:

//have T tObj;
var sExpr = s.Body as MemberExpression;
var sProp = typeof(T).GetProperty(sExpr.Member.Name);
var sVal = dProp.GetValue(tObj, null);

For some reason sVal is never considered to be null by the compiler/resharper (i'm not sure which one is showing the warning). I don't get possible null reference warnings at design time. If I create a condition like if(sVal == null) I'll get a design time warning that the expression is always false.

sVal is just an object, and objects can be null. I don't think GetValue guarantees never to return null. What's going on?

Upvotes: 0

Views: 624

Answers (1)

Alex
Alex

Reputation: 9429

John Skeet was right. I was checking for null after working with the variable. I rearranged my code to do the null check BEFORE working with the variable and the problem went away. What strange is that I didn't get a null reference warning before and I should have.

Upvotes: 1

Related Questions