Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ReSharper suggesting a possible NullReferenceException on a dynamic type?

If I write the following code, ReSharper is warning me for a possible NullReferenceException. However I'm explicitly checking for null in the statement above. Is there something about dynamic I do not know about (is it assuming it might be backed by a IEnumerable or something like that)? Or is this a glitch with ReSharper? Or something else?

dynamic user = connection.Query("SELECT ...").FirstOrDefault(); // Dapper Extension
if (user == null)
    return null;

return new User(user.username);
//              ^^^^
// (local variable) dynamic user
//
// Possible 'System.NullReferenceException'
like image 824
Rick Avatar asked Mar 26 '13 16:03

Rick


2 Answers

The issue is that user == null is a dynamic call; R# can't assume that the runtime type of the user object will have an equality operator that works properly. It could very easily have:

public static bool operator ==(Foo x, Foo y) { return false; }
public static bool operator !=(Foo x, Foo y) { return true; }

in which case, user == null would always return false, even if the user variable was a null reference.

Try changing the code to:

if (ReferenceEquals(user, null)) return null;
return new User(user.username);

NB: The problem only appears when you have the "Assume entity value can be null" option set to "When entity doesn't have explicit NotNull attribute".

like image 62
Richard Deeming Avatar answered Oct 23 '22 12:10

Richard Deeming


Try this :

dynamic user = connection.Query("SELECT ...").FirstOrDefault(); // Dapper Extension
if (user != null)
    return new User(user.username);

return null;
like image 45
o0alex0o Avatar answered Oct 23 '22 12:10

o0alex0o