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?
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.
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);
}
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