8

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'
Rick
  • 3,361
  • 1
  • 22
  • 29

2 Answers2

5

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".

Richard Deeming
  • 29,830
  • 10
  • 79
  • 151
1

Try this :

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

return null;
o0alex0o
  • 23
  • 7