Why does Resharper show a System.NullReferenceException
warning in this case?
MethodBase.GetCurrentMethod().DeclaringType.Name
I am having the above line in many places in my code. Why does Resharper throw me a warning?
I checked SO for questions on similar line but no exact match is there.
A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.
The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement.
What you're seeing is the result of ReSharper's Annotation [CanBeNull]
, that is applied to the property MemberInfo.DeclaringType
:
(This is ReSharper's QuickDoc feature, press Ctrl+Q or Ctrl+Shift+F1, depending on the key bindings you use, on the property).
I recently recorded a webinar with JetBrains, discussnig Annotations in depth, so you're welcome to watch it for more information about how this works, but basically, ReSharper "knows" that the DeclaringType
property can be potentially null at runtime. This is because any one of the MemberInfo
implementations can return null, potentially, from this property. For example, ConstructorInfo
does this:
public override Type DeclaringType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
}
}
In any event, since potentially, one of the implementations of DeclaringType
can be a null, ReSharper warns you about it, so you need to do a null check.
Because GetCurrentMethod() could presumeably return null and when it tries to access .DeclaringType it will then fail with your error. It is suggesting you run GetCurrentMethod() and check its result defensively prior to accessing the property. This is the same for DeclaringType and accessing the Name property
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