Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine tuple types?

Tags:

c#

.net

tuples

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.

like image 222
toplel32 Avatar asked Feb 27 '15 18:02

toplel32


People also ask

How do you know what type a tuple is?

Method #1: Using type() This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well.

What are different types of tuples?

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). A tuple can also be created without using parentheses. This is known as tuple packing.

How do you check if a tuple is in a tuple?

Method #1: Using any() any function is used to perform this task. It just tests one by one if the element is present as the tuple element. If the element is present, true is returned else false is returned.

Can tuple have different data types?

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). A tuple can also be created without using parentheses.


1 Answers

Try this:

public static bool IsTupleType(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;
}
like image 160
rtf_leg Avatar answered Oct 15 '22 16:10

rtf_leg