8

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?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
Mohammad Zargarani
  • 1,422
  • 2
  • 12
  • 19
  • 5
    Look [here](http://stackoverflow.com/questions/3679562/generic-methods-and-method-overloading), the question is basically the same – Save Sep 22 '13 at 09:01
  • 5
    The exact rules for overload precedence are complicated and in the specification: but I suspect it is actually calling `Get(Student)` - which is an exact match; `Get(Person)` is *not* an exact match because you are passing a Student, not a Person – Marc Gravell Sep 22 '13 at 09:04

1 Answers1

12

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.

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93