Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#-4.0

Is there any built in conversion or cast between KeyValuePair<T1, T2> and Tuple<T1, T2>?

I know this would 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<> was often used in place of a 2 element Tuple<> until it's addition to C#4.0), I was wondering if such a converter was already built into the framework?

Reason I ask is I am working with an older library (targeting .NET 3.5) that used KeyValuePair<> in many places that a 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 cast or convert the return kvp values from these methods to Tuple or if I need to define my own conversion (or change the older code).

like image 750
psubsee2003 Avatar asked Aug 15 '12 14:08

psubsee2003


1 Answers

There is no built-in conversion in the BCL that I'm aware of, and there's definitely no implicit or explicit cast. I doubt they'd ever add this conversion because the types are used for different purposes.

I think your version is fine.

like image 194
Kit Avatar answered Nov 23 '22 07:11

Kit