Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call generic method in c# [duplicate]

Tags:

c#

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?

like image 920
Mohammad Zargarani Avatar asked Sep 22 '13 08:09

Mohammad Zargarani


People also ask

How do you call a generic class in C#?

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.

How do I use reflection to call a generic method?

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");

What is the syntax for generic function?

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.


1 Answers

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.

like image 156
Ondrej Janacek Avatar answered Oct 13 '22 17:10

Ondrej Janacek