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

  • A+
Category:Languages
 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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: