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).
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.
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