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'
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".
Try this :
dynamic user = connection.Query("SELECT ...").FirstOrDefault(); // Dapper Extension
if (user != null)
return new User(user.username);
return null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With