Is it worth saving the result of calling typeof () for multiple use?

If I have to use the result of a C # type call of the same type, is it worth saving the value or just calling typeof () several times. For me, several types are preferable, as this may be more concise, readable code. I think it depends on whether the compiler will "embed" the code?

+7
source share
1 answer

No, typeof() is a compilation keyword.

There may be a slight advantage in storing the result of object.GetType() in the Type variable.


Update

 Type t = typeof(string); 

This is what this line compiled for

 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, he will use GetTypeFromHandle , which, it seems to me, is here a pointer to the location of the type on the heap.

Thus, there may be a slight advantage when invoking it once and maintaining the link, although it will be negligible.

+8
source

All Articles