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

StackOverflow https://stackoverflow.com/questions/22809141

  •  26-06-2023
  •  | 
  •  

Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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

The signature of GetCurrentMethod is :

public static System.Reflection.MethodBase GetCurrentMethod()

Since it's return type is a reference type , which is followed by access to property , R# can't know if the method GetCurrentMethod returnd null or not. You know it. R# - doesn't know.

Because either GetCurrentMethod or DeclaringType could return a null, and you cannot access null object's property.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top