Type Helper
Simple helpers when using types.
using System;
using System.Collections.Generic;
using System.Text;
namespace Library.Reflection
{
/// <summary>
/// Simple information about types.
/// </summary>
public static class TypeHelper
{
/// <summary>
/// If it's a nullable value type, returns the base type (eg int? is int).
/// Non-nullable value types and reference types are returned.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
public static Type GetNonNullableType(Type type)
{
if (IsNullableType(type))
type = type.GetGenericArguments()[0];
return type;
}
/// <summary>
/// Determines whether type is a dateTime or nullable dateTime.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if [is date time] [the specified type]; otherwise, <c>false</c>.
/// </returns>
public static bool IsDateTime(Type type)
{
if (type == null) return false;
type = GetNonNullableType(type);
return (type == typeof(DateTime));
}
/// <summary>
/// Determines whether the specified type is nullable.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the specified type is nullable; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullable(Type type)
{
if (type == null) return false;
//reference types are always nullable
if (!type.IsValueType) return true;
//if it's Nullable<int> it IsValueType, but also IsGenericType
return IsNullableType(type);
}
/// <summary>
/// Determines whether the specified type is a numeric type or nullable numeric type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the specified type is numeric; otherwise, <c>false</c>.
/// </returns>
/// <remarks>Note that List<int> is not numeric.</remarks>
public static bool IsNumeric(Type type)
{
if (type == null) return false;
type = GetNonNullableType(type);
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
return false;
}
/// <summary>
/// Determines whether the specified type is a string.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the specified type is a string; otherwise, <c>false</c>.
/// </returns>
public static bool IsString(Type type)
{
if (type == null) return false;
return (type == typeof(string));
}
private static bool IsNullableType(Type type)
{
return (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)));
}
}
}