Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a generic parameter on overloaded methods

Why does this program output Generic Value and not Hello world!:

using System;

class Example
{
    public static void Print<T>(T value)
    {
        Console.WriteLine("Generic Value");
    }

    public static void Print(string value)
    {
        Console.WriteLine(value);
    }

    public static void GenericFunc<T>(T value)
    {
        Print(value);
    }

    static void Main()
    {
        GenericFunc("Hello world!");
    }
}

How is the generic method parameter being translated under the hood of C#?

like image 749
nullptr Avatar asked Dec 08 '22 23:12

nullptr


1 Answers

Overload resolution is only done at compile-time.

Since GenericFunc<T> doesn't know whether T is a string or something else at compile-time, it can only ever use the Print<T>(T value) "overload".

Using dynamic, you can change this to a dynamic dispatch, and get the behaviour you expect:

Print((dynamic)value);

This makes the overload resolution happen at runtime, with the actual runtime type of value.

like image 94
Luaan Avatar answered Dec 11 '22 09:12

Luaan