Wednesday, July 30, 2008

This method indicates whether an object is numeric or not.  Handy in reflection type situations when you need to perform and action based on type.

private static bool IsNumeric(Object o)
{
    if((o is int) || (o is int?) ||
        (o is decimal) || (o is decimal?) ||
        (o is double) || (o is double?) ||
        (o is float) || (o is float?) ||
        (o is long) || (o is long?) ||
        (o is ulong) || (o is ulong?) ||
        (o is ushort) || (o is ushort?) ||
        (o is short) || (o is short?) ||
        (o is byte) || (o is byte?) ||
        (o is sbyte) || (o is sbyte?) ||
        (o is uint) || (o is uint?))
        
        return true;
    
    return false;
}


It's long and a bit ugly but it's the only way I've found.

Wednesday, July 30, 2008 1:24:38 PM (Central Standard Time, UTC-06:00)  #    Comments [1]
Thursday, July 31, 2008 9:00:54 AM (Central Standard Time, UTC-06:00)
There is no need to compare with nullables. A variable of type Object always has a type, or it is null. The CLR will always extract the value part of a nullable variable before passing it to a method which accepts an Object parameter.

From the MSDN documentation:

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable<(Of <(T>)>) object, not the Nullable<(Of <(T>)>) object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable<(Of <(T>)>) structure initialized to the underlying value.

If the HasValue property of a nullable type is false, the result of a boxing operation is nullNothingnullptra null reference (Nothing in Visual Basic). Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is nullNothingnullptra null reference (Nothing in Visual Basic). When nullNothingnullptra null reference (Nothing in Visual Basic) is unboxed into a nullable type, the common language runtime creates a new Nullable<(Of <(T>)>) structure and initializes its HasValue property to false.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):