andrew4582

TypeHelper

Aug 2nd, 2011
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. internal static class TypeHelper {
  2.         internal static bool IsEnumerableType(Type enumerableType) {
  3.             return FindGenericType(typeof(IEnumerable<>), enumerableType) != null;
  4.         }
  5.         internal static bool IsKindOfGeneric(Type type, Type definition) {
  6.             return FindGenericType(definition, type) != null;
  7.         }
  8.         internal static Type GetElementType(Type enumerableType) {
  9.             Type ienumType = FindGenericType(typeof(IEnumerable<>), enumerableType);
  10.             if (ienumType != null)
  11.                 return ienumType.GetGenericArguments()[0];
  12.             return enumerableType;
  13.         }
  14.         internal static Type FindGenericType(Type definition, Type type) {
  15.             while (type != null && type != typeof(object)) {
  16.                 if (type.IsGenericType && type.GetGenericTypeDefinition() == definition)
  17.                     return type;
  18.                 if (definition.IsInterface) {
  19.                     foreach(Type itype in type.GetInterfaces()) {
  20.                         Type found = FindGenericType(definition, itype);
  21.                         if (found != null)
  22.                             return found;
  23.                     }
  24.                 }
  25.                 type = type.BaseType;
  26.             }
  27.             return null;
  28.         }
  29.         internal static bool IsNullableType(Type type) {
  30.             return type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
  31.         }
  32.         internal static Type GetNonNullableType(Type type) {
  33.             if (IsNullableType(type)) {
  34.                 return type.GetGenericArguments()[0];
  35.             }
  36.             return type;
  37.         }
  38.     }
Advertisement
Add Comment
Please, Sign In to add comment