I recently read and article about .GetType () and Typeof () methods in c#. Now, I know that both of them return System. Type. That article also indicated that it's important to know .GetType () gets resolved at run-time while the other one does at compile-time.
I wonder why it should be considered this fact? Having in mind that the return value of both functions is the same, why we need to know 'when' they get resolved?
Thank you
typeof
isn't a method - it's an operator. That's how it's resolved at compile time. They don't do the same thing, in that for typeof
you need to know the actual type or type parameter1 you want at compile-time, whereas for GetType
you don't. For example:
Stream x = GetStreamFromSomewhere();
Type t1 = typeof(Stream); // Always exactly System.IO.Stream
Type t2 = x.GetType(); // Never System.IO.Stream
t2
can never be System.IO.Stream
, because that's an abstract type. It could be System.IO.MemoryStream
, System.IO.FileStream
, or some kind of stream subclass that didn't even exist when I wrote this code. It's the type of the actual object that the value of x
refers to. That will always be a stream of some kind, but we don't know until we ask what the type actually is.
1 If you're using typeof(T)
then the actual type isn't know by that piece of code at compile-time, but it's the type argument for any particular call. It's not using the execution-time type of a particular object.
See more on this question at Stackoverflow