Why does Resharper show a System.NullReferenceException warning in this case?

c#, resharper

Solution

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.

Problem

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.

Original source