toplel32 toplel32 - 22 days ago 14
C# Question

How to determine tuple types?

Apparently

ITuple
is internal, disabling a solution such as
typeof(ITuple).IsAssignableFrom(type)
. By alternative, what is the most effective way to determine
Tuple<>
till
Tuple<,,,,,,,>
? A solution without type name comparison is preferable.

Answer

Try this:

public static bool IsTypeOfTuple(Type type, bool checkBaseTypes = false)
{
    if (type == null)
        throw new ArgumentNullException(nameof(type));

    if (type == typeof(Tuple))
        return true;

    while (type != null)
    {
        if (type.IsGenericType)
        {
            var genType = type.GetGenericTypeDefinition();
            if (genType == typeof(Tuple<>)
                || genType == typeof(Tuple<,>)
                || genType == typeof(Tuple<,,>)
                || genType == typeof(Tuple<,,,>)
                || genType == typeof(Tuple<,,,,>)
                || genType == typeof(Tuple<,,,,,>)
                || genType == typeof(Tuple<,,,,,,>)
                || genType == typeof(Tuple<,,,,,,,>)
                || genType == typeof(Tuple<,,,,,,,>))
                return true;
        }

        if (!checkBaseTypes)
            break;

        type = type.BaseType;
    }

    return false;
}
Comments