7

Resharper tells me that MemberInfo.DeclaringType can never be null: enter image description here

However when that code is run, the text "Top level member" is printed. I don't get it, what's wrong here?

JBSnorro
  • 6,048
  • 3
  • 41
  • 62
  • Did you do a full clean and rebuild? Often resharper puts up odd warnings because it hasn't rerun its analysis recently enough. Otherwise it may just be a bug. – captncraig Apr 21 '11 at 17:07
  • @CMP, jep I did. And I find it strange that this would be a bug, since the attributes such as NotNullAttribute, are automatically assigned to standard libraries. If there was a bug in that code, that must have been noticed before. – JBSnorro Apr 21 '11 at 17:09
  • I meant a bug in resharper's static analysis engine. – captncraig Apr 21 '11 at 17:13
  • [MemberInfo.DeclaringType's documentation](http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.declaringtype.aspx) even says it will return null in some cases. – Austin Salonen Apr 21 '11 at 17:14
  • Related: http://stackoverflow.com/questions/35266010/can-propertyinfo-declaringtype-really-ever-be-null – user2864740 Oct 27 '16 at 23:53

2 Answers2

10

Microsoft Code Contracts states that it is never null.

// System.Reflection.MemberInfo
public virtual Type DeclaringType
{
    get
    {
        Contract.Ensures(Contract.Result<Type>() != null, null, "Contract.Result<Type>() != null");
        Type result;
        return result;
    }
}

So ReSharper relies on Code Contracts here.

Evgeny Pasynkov
  • 693
  • 4
  • 5
  • Ok, I've posted it on the code contracts forum, http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/fdf1436a-e843-408c-b932-c012e03e72cd – JBSnorro Apr 22 '11 at 10:37
6

Resharper is simply wrong here. MemberInfo is an abstract type and it's possible for an arbitrary implementation to return whatever it pleases including null

Example:

class EvilMemberInfo : MemberInfo
{
    public override System.Type DeclaringType
    {
        get { return null; }
    }

    // Rest omitted for brevity
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    That's exactly the override System.Type uses for DeclaringType. Maybe they should call it EvilType. =] – rsbarro Apr 21 '11 at 17:14
  • I recently claimed to have found a bug in Resharper, but it turned out I was wrong. This time however, I stated my question a bit less aggressive, but I do agree with you. – JBSnorro Apr 21 '11 at 17:14
  • @rsbarro, no! That's not exactly the override for System.Type, since types can be nested.... – JBSnorro Apr 21 '11 at 17:15
  • @JBSnorro Not following you there. Looking in ILSpy, System.Type is abstract, it overrides the DeclaringType property, and it returns null on the getter. What am I missing? – rsbarro Apr 21 '11 at 17:20
  • @rsbarro, I was thinking of the scenario class Foo{public class Bar{}}, where typeof(Foo.Bar).DeclaringType is not null. But you're correct, sorry :P – JBSnorro Apr 21 '11 at 17:25