Consider this code:
static void Main(string[] args)
{
Get<Student>(new Student());
System.Console.Read();
}
public static void Get<T>(T person)
{
Console.WriteLine("Generic function");
}
public static void Get(Person person)
{
person.Show();
}
This my Person Class:
class Person
{
public void Show()
{
Console.WriteLine("I am person");
}
}
class Student : Person
{
public new void Show()
{
Console.WriteLine("I am Student");
}
}
I call Get
and pass student to the method.Like this:
Get<Student>(new Student());
So i get this: Generic function
.But when i call Get
like this:
Get(new Student());
I expect thisGet(Person person)
to be called.but again call:Get<T>(T person)
.
Why Compiler has this behavior?
A type parameter is a placeholder for a particular type specified when creating an instance of the generic type. A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
The first step to dynamically invoking a generic method with reflection is to use reflection to get access to the MethodInfo of the generic method. To do that simply do this: var methodInfo = typeof(ClassWithGenericMethod). GetMethod("MethodName");
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.
I can refer you the Jon Skeet's book C# in Depth (second edition for now), a chapter number 9.4.4. I altered the text to fit in you situation.
Picking the right overloaded method
At this point, the compiler considers the conversion from Student to Student, and from Student to Person. A conversion from any type to itself is defined to be better than any conversion to a different type, so the Get(T x) with T as a Student method is better than Get(Person y) for this particular call.
There is a slighly more explanation in the book and I can at least strongly recommend you to read it thoroughly.
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