H Bellamy
H Bellamy

Reputation: 22715

Can a ConstructorInfo have no DeclaringType

I was browsing the System.Linq.Expressions source code on GitHub and found the following code

public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments)
{
    ContractUtils.RequiresNotNull(constructor, nameof(constructor));
    ContractUtils.RequiresNotNull(constructor.DeclaringType, nameof(constructor));

    // ...
}

I was confused by the second null check, so went to MSDN. It had the following to say about ConstructorInfo.DeclaringType:

The DeclaringType property retrieves a reference to the Type object for the type that declares this member. A member of a type is either declared by the type or inherited from a base type, so the Type object returned by the DeclaringType property might not be the same as the Type object used to obtain the current MemberInfo object.

If the Type object from which this MemberInfo object was obtained did not declare this member, the DeclaringType property will represent one of its base types.

If the MemberInfo object is a global member (that is, if it was obtained from the Module.GetMethods method, which returns global methods on a module), the returned DeclaringType will be null.

So it seems that DeclaringType can be null for a MemberInfo (the class from which ConstructorInfo derives). But I am uncertain whether it can be null or not for ConstructorInfo.

So to my questions:

  1. Can ConstructorInfo.DeclaringType ever be null? Why is the System.Linq.Expressions code checking for it?

  2. If DeclaringType can be null, can you provide an example?

  3. If DeclaringType can be null, does this imply that the CLR supports global constructors? (I've tried researching this but can't find anything)

Upvotes: 2

Views: 203

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70691

Here's the source code for ConstructorInfo.DeclaringType:

public override Type DeclaringType 
{ 
    get 
    { 
        return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; 
    }
}

I don't have a specific example of this scenario, but given that this is the ConstructorInfo class itself, it seems pretty clear to me it was specifically written with the possibility that its DeclaringType property could return null.

I doubt you could cause this to happen with C# code, but the CLR supports a wide variety of languages. C++/CLI seems like the most likely culprit to me for this scenario, as a C++/CLI assembly winds up with a bunch of boilerplate and global members, but VB.NET also does some global stuff as well. Presumably, one could generate IL directly that would also create this situation.

Upvotes: 2

Related Questions