Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method takes KeyValuePair. How do I forward the call to the correct overload taking the Key type?

 class Program
    {
        static void Main(string[] args)
        {

        }

        void DoSomething(int a)
        {
            Console.WriteLine("int");
        }
        void DoSomething(char a)
        {
            Console.WriteLine("char");
        }
        void DoSomething<T, U>(KeyValuePair<T, U> a)
        {
            DoSomething(a.Key);
        }
    }

I have a third-party assembly that has a huge struct with lots of members of different types in it. I need to take some of the values from that struct and process them. So I write overloads for different types. I know what I need to do with ints, with chars, etc. And if some value is a key value pair, I know I need to process only the key the same way I would process a primitive value. The code above is my failed attempt to do so. The problem is that the C# compiler complains that it cannot determine which overload to call for a.Key because, unlike C++, where it would instantiate the template and then automagically know exactly which overload to call or fail with a compiler error, C# doesn't do this.

Is there something basic I'm missing, and if not, what is the usual C# idiom to solve the design problem I'm facing?

like image 571
Armen Tsirunyan Avatar asked Sep 19 '18 12:09

Armen Tsirunyan


2 Answers

One hacky way is to cast a.Key to dynamic:

DoSomething((dynamic)a.Key);

The correct overload will be determined at runtime. If there are no appropriate overloads then you will get an exception.

like image 180
Selman Genç Avatar answered Sep 21 '22 13:09

Selman Genç


If you are 100% confident that T will be int or char - then dynamic is one approach to consider:

static void DoSomething<T, U>(KeyValuePair<T, U> a)
{
    dynamic bob = a.Key;
    DoSomething(bob);
}
like image 20
mjwills Avatar answered Sep 22 '22 13:09

mjwills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!