ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

IsNumeric

Returns true if the type can be considered numeric

Source

public static bool IsNumeric(this Type t)
{
	var type = t.GetTypeWithoutNullability();
	return
		type == typeof (Int16) ||
		type == typeof (Int32) ||
		type == typeof (Int64) ||
		type == typeof (UInt16) ||
		type == typeof (UInt32) ||
		type == typeof (UInt64) ||
		type == typeof (decimal) ||
		type == typeof (float) ||
		type == typeof (double);
}

public static Type GetTypeWithoutNullability(this Type t)
{
	return t.IsNullable() ? new NullableConverter(t).UnderlyingType : t;
}

public static bool IsNullable(this Type t)
{
	return t.IsGenericType &&
		   t.GetGenericTypeDefinition() == typeof (Nullable<>);
}

Example

if (someType.IsNumeric())
{
    do something that requires type be numeric
}

Author: Tim Scott (lunaverse.wordpress.com)

Submitted on: 18 okt 2010

Language: C#

Type: System.Type

Views: 4075