Downcasting a Tuple

by mandel on December 26th, 2010

I’m currently working on a “small” pet project (that I want to take advantage of at some point) in which I’m json serializing (Json.Net) a Tuple in which the Item type can be of any kind. Of course when deserializing the object, I’d like to have my object type as close as possible to its original type, that is, if I serialized a Tuple<string> I want to get the same object type and not a Tuple<object>.

To solve this I have written the following small extension method to do the job using Reflection:

/// <summary>
/// Downcast the more generic tuple with an object type 
/// to a more specific one.
/// </summary>
/// <param name="tuple">The tuple to down cast.</param>
/// <returns>The downcasted instance of the object.</returns>
public static object DownCast(this Tuple<object> tuple)
    var tupleType = typeof (Tuple<>);
    var downcast = tupleType.MakeGenericType(tuple.Item1.GetType());
    return Activator.CreateInstance(downcast, tuple.Item1);

The same idea can be used for any type of tuple (Tuple<,>, Tuple<,,> etc…). I hope this small code helps someone else :)