Conversion between Tuple <T1, T2> and KeyValuePair <T1, T2>

Is there a built-in transform or cast between KeyValuePair<T1, T2> and Tuple<T1, T2> ?

I know this will be a trivial extension method:

 public static KeyValuePair<T1, T2> ToPair<T1, T2>(this Tuple<T1, T2> source) { return new KeyValuePair<T1, T2>(source.Item1, source.Item2); } public static Tuple<T1, T2> ToTuple<T1, T2>(this KeyValuePair<T1, T2> source) { return Tuple.Create(source.Key, source.Value); } 

But since objects can be used for similar purposes (especially since KeyValuePair<> often used instead of 2 Tuple<> elements until it added to C # 4.0), I was wondering if such a converter was already built-in in the framework?

The reason I'm asking is because I am working with an older library (targeting .NET 3.5) that used KeyValuePair<> in many places, that Tuple might be more appropriate, and I want to use Tuple<> in the new code. so I'm trying to figure out if I can just use or convert return kvp from these methods to Tuple or do I need to define my own conversion (or change the old code).

+6
source share
1 answer

There is no built-in conversion in BCL that I know of, and no unambiguous or explicit cast. I doubt they have ever added this conversion because types are used for different purposes.

I think your version is fine.

+6
source

Source: https://habr.com/ru/post/922946/


All Articles