Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Should be pretty self-explanatory, but this is in the context of real-time XNA code where I want to avoid allocations in order to avoid triggering GC. So I'm wondering if the managed Type objects associated with the types that have been loaded are always present in the runtime, or if typeof() actually constructs a new Type object (presumably from some unmanaged metadata in the runtime) on the heap, which will be garbage collected. Feel free to point out any ignorant assumptions/misconceptions revealed by even asking this question as well =)

like image 301
Max Strini Avatar asked Oct 21 '11 22:10

Max Strini


People also ask

What is typeof () in C?

The typeof keyword is a new extension to the C language. The Oracle Developer Studio C compiler accepts constructs with typeof wherever a typedef name is accepted, including the following syntactic categories: Declarations. Parameter type lists and return types in a function declarator.

What is the use of typeof ()?

The typeof operator is used to get the data type (returns a string) of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type.

Does typeof return a string?

typeof is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, typeof will return "undefined" instead of throwing an error.

What is typeof keyword?

Typeof in JavaScript is an operator used for type checking and returns the data type of the operand passed to it. The operand can be any variable, function, or object whose type you want to find out using the typeof operator.


1 Answers

From the C# 4 spec section 7.6.11:

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

(Additionally, if you get the type via reflection it will always fetch the same Type object too, but that's not in the spec.)

like image 78
Jon Skeet Avatar answered Oct 06 '22 23:10

Jon Skeet