-
-
Save suzhou01/7f3985f164bb3159e0ee28d7555fb331 to your computer and use it in GitHub Desktop.
A way to check if a type is numeric in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ch.cimnine.Util | |
{ | |
public sealed class Numeric | |
{ | |
/// <summary> | |
/// Determines if a type is numeric. Nullable numeric types are considered numeric. | |
/// </summary> | |
/// <remarks> | |
/// Boolean is not considered numeric. | |
/// </remarks> | |
public static bool Is(Type type) | |
{ | |
if (type == null) return false; | |
// from http://stackoverflow.com/a/5182747/172132 | |
switch (Type.GetTypeCode(type)) | |
{ | |
case TypeCode.Byte: | |
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; | |
case TypeCode.Object: | |
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) | |
{ | |
return Is(Nullable.GetUnderlyingType(type)); | |
} | |
return false; | |
} | |
return false; | |
} | |
/// <summary> | |
/// Determines if a type is numeric. Nullable numeric types are considered numeric. | |
/// </summary> | |
/// <remarks> | |
/// Boolean is not considered numeric. | |
/// </remarks> | |
public static bool Is<T>() | |
{ | |
return Is(typeof(T)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment