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?
No, typeof()
is a compile-time keyword.
There could be a small benefit in keeping result of object.GetType()
in a Type
variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With