Say I have an System.String[] type object. I can query the type object to determine if it is an array
Type t1 = typeof(System.String[]);
bool i
Thanks to @psaxton comment pointing out the difference between Array and other collections. As an extension method:
public static class TypeHelperExtensions
{
///
/// If the given is an array or some other collection
/// comprised of 0 or more instances of a "subtype", get that type
///
/// the source type
///
public static Type GetEnumeratedType(this Type type)
{
// provided by Array
var elType = type.GetElementType();
if (null != elType) return elType;
// otherwise provided by collection
var elTypes = type.GetGenericArguments();
if (elTypes.Length > 0) return elTypes[0];
// otherwise is not an 'enumerated' type
return null;
}
}
typeof(Foo).GetEnumeratedType(); // null
typeof(Foo[]).GetEnumeratedType(); // Foo
typeof(List).GetEnumeratedType(); // Foo
typeof(ICollection).GetEnumeratedType(); // Foo
typeof(IEnumerable).GetEnumeratedType(); // Foo
// some other oddities
typeof(HashSet).GetEnumeratedType(); // Foo
typeof(Queue).GetEnumeratedType(); // Foo
typeof(Stack).GetEnumeratedType(); // Foo
typeof(Dictionary).GetEnumeratedType(); // int
typeof(Dictionary).GetEnumeratedType(); // Foo, seems to work against key