If I have the following code
private BaseMessage getMessage()
{
return new OtherMessage();
}
private void CheckType<T>(T type)
{
Console.WriteLine(type.GetType().ToString());
Console.WriteLine(typeof(T).ToString());
}
private void DoChecks()
{
BaseMessage mess = getMessage();
CheckType(mess);
}
why do I get different types outputted? Is there anyway of getting the type inference to use the actual type of the object being passed?
Generic type inference means that the compiler automatically resolves the types of the arguments being passed without the need of you explicitly specifying what type you're passing. This means that this is done in compile-time: in your code, during the compilation, the compiler only knows about BaseMessage, so the parameter will be passed as BaseMessage. During the run-time, the parameter's actual type will be OtherMessage, but that is of no concern to the compiler.
Therefore, the output you're getting is absolutely valid. I don't know any ways do overcome this issue, apart from always using Object.GetType instead of typeof().
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