Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof(T) may return null

Tags:

c#

clr

clr4.0

When using the typeof operator on type created through TypeBuilder, the operator will return null.

I'm curious why this happens and how to prevent it.


I'm starting to think this is a VS bug in the immediate window, but I'm not quite sure. It's very easy to blame others first.

Ok... code to reproduce issue:

    static void Main()
    {
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
            new AssemblyName("MyAssembly"),
            AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule");
        TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public, typeof(ArrayList));

        ArrayList o = (ArrayList)Activator.CreateInstance(typeBuilder.CreateType());

        Console.WriteLine(o.GetType().Name);
    }

If you put a breakpoint after the variable o and type typeof(MyType) in the VS Immediate Windows you'll get the issue.

like image 758
redb Avatar asked Jun 27 '11 18:06

redb


People also ask

Can Typeof return null?

The typeof operator returns "object" for objects, arrays, and null.

Can return null c#?

A primary limitation of collections is the absence of effective type checking. This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. Also, we cannot simply return null from a generic method like in normal method.


1 Answers

When using the typeof operator on type created through TypeBuilder, the operator will return null.

First of all, the claim is correct. If you write this program and then stop it in the debugger and say "typeof(MyType)" in the immediate window, the result that comes back is "null".

I'm curious why this happens

Beats the heck out of me. If I had to guess, I'd say that maybe the expression evaluator is communicating with the CLR's debugging subsystem to try and get a metadata token for the type by its name, and the CLR is returning some garbage nil token rather than producing an error.

I hasten to emphasize that this is a guess; I have not actually debugged it.

I'm starting to think this is a VS bug in the immediate window

That seems likely. The correct thing that it should be doing is giving the error "the type or namespace 'MyType' is not valid in this scope". The bug will almost certainly be in the C# runtime expression evaluator, not in the immediate window itself.

Thanks for bringing the issue to my attention. I'll file a bug with the expression evaluator maintainers and we'll see if they can address the issue.

how to prevent it?

If it hurts when you type "typeof(MyType)" then stop typing that.

like image 193
Eric Lippert Avatar answered Oct 26 '22 18:10

Eric Lippert