Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can GetTypeInfo ever return null?

I am rewriting some code (targeting .NET 4.5.2. currently) that uses reflection to compile for .NET Standard 1.4. I therefore need to use GetTypeInfo() on a Type at many places.

In order to handle the edge cases correctly, my question is, can GetTypeInfo() ever return null? The documentation (https://msdn.microsoft.com/en-us/library/system.reflection.introspectionextensions.gettypeinfo(v=vs.110).aspx) is silent about this.

When I open a source of GetTypeInfo() from a standard .NET 4.5.2 project, I get:

public static class IntrospectionExtensions
{
    public static TypeInfo GetTypeInfo(this Type type){
        if(type == null){
            throw new ArgumentNullException("type");
        }
        var rcType=(IReflectableType)type;
        if(rcType==null){
            return null;
        }else{
            return rcType.GetTypeInfo();
        }
    }   
}

That is still confusing. There is a code branch that returns null when '(IReflectableType)type' is null, but why? - the 'type' itself is checked against null before, and an exception is thrown when it is null, therefore I cannot see how 'rcType' can ever be null (mind you, this is not an 'as' operator, it is a straight typecast).

In a good tradition, the documentation on IReflectableType.GetTypeInfo (, https://msdn.microsoft.com/en-us/library/system.reflection.ireflectabletype.gettypeinfo(v=vs.110).aspx ) is also silent about the possibility of a null outcome.

A code that uses reflection needs to use GetTypeInfo at many places, and if a null results is allowed, it would therefore require to have a null check and a corresponding action at every such place. I have checked other people's code (including Microsoft's own example at https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 ) and developers seem to be treating it as a null result was not possible. Is that correct?

like image 296
ZbynekZ Avatar asked Aug 30 '17 08:08

ZbynekZ


1 Answers

GetTypeInfo() is never supposed to return null.

See the new code in .NET Core and the comment that Microsoft people who ported this code left.

like image 85
Kostya Avatar answered Nov 11 '22 07:11

Kostya