Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

resharper

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.

like image 455
ckv Avatar asked Apr 02 '14 10:04

ckv


People also ask

What does system NullReferenceException mean?

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.

How do I stop NullReferenceException?

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.


2 Answers

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.

like image 59
Igal Tabachnik Avatar answered Nov 10 '22 19:11

Igal Tabachnik


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

like image 32
sarin Avatar answered Nov 10 '22 20:11

sarin