Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it worth saving the result of the typeof() call for multiple uses?

If I am to use the result of the C# typeof call on the same type, is it worth saving the value, or just call typeof() multiple times. To me, multiple typeof's are preferable as it can more concise, readable code. I guess it depends on whether the compiler would 'inline' the code?

like image 315
Lee Atkinson Avatar asked Mar 08 '11 21:03

Lee Atkinson


1 Answers

No, typeof() is a compile-time keyword.

There could be a small benefit in keeping result of object.GetType() in a Type variable.


Update

Type t = typeof(string);

This is what this line is compiled to

IL_0000:  nop
  IL_0001:  ldtoken    [mscorlib]System.String
  IL_0006:  call       class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
  IL_000b:  stloc.0
  IL_000c:  ldloc.0

So internally, it will use GetTypeFromHandle which I imagine handle here is a pointer to the location of type in the heap.

So there can be a tiny little benefit in calling it once and keeping the reference, although will be minuscule.

like image 167
Aliostad Avatar answered Nov 14 '22 11:11

Aliostad