Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does generic type inference work in C#?

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?

like image 215
chris Avatar asked Apr 15 '26 10:04

chris


1 Answers

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().

like image 152
ShdNx Avatar answered Apr 17 '26 22:04

ShdNx