Does typeof () operator in C # allocate a new type object on the heap or return an existing one?

It should be pretty clear, but this is in the context of real-time XNA code, where I want to avoid allocation in order to avoid starting GC. So I wonder if the managed Type objects associated with the loaded types are always at runtime, or if typeof () actually creates a new Type object (presumably from some unmanaged metadata at runtime) on the heap that will garbage collect. Feel free to indicate any uninformed assumptions / misconceptions identified even by asking this question =)

+7
source share
2 answers

No, types are cached, it always returns the same static readonly instance.

You can write this test test program to see this :)

static void MyTest() { if (object.ReferenceEquals(typeof(int), typeof(int)) Console.WriteLine("Yippie! they are the same!"); else Console.WriteLine("WTF?"); } 

The same goes for the GetType method for any other reflection function, for example, getting properties, methods, fields, attributes, and everything else.

+15
source

From the C # 4 specification section 7.6.11:

For any given type, there is only one System.Type object. This means that for type T , typeof(T) == typeof(T) always true.

(Also, if you get a type through reflection, it will always get the same Type object, but that's not in the specification.)

+15
source

All Articles