How to determine the types of tuples?

ITuple be internal, disabling a solution like typeof(ITuple).IsAssignableFrom(type) . Alternatively, what is the most efficient way to define Tuple<> to Tuple<,,,,,,,> ? A solution without comparing type names is preferred.

+6
source share
2 answers

Try the following:

 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; } 
+12
source

I know that OP does not prefer type name matching, but for reference, I include this short solution that determines if the type is the root value:

 var x = (1, 2, 3); var xType = x.GetType(); var tType = typeof(ValueTuple); var isTuple = xType.FullName.StartsWith(tType.FullName) 

You can add xType.Assembly == tType.Assembly to be sure.

-1
source

Source: https://habr.com/ru/post/983122/


All Articles