2

I have created a test code snippet demonstrating what I am trying to achieve. But it does not work as expected (see comments in code):

public class Program
{
    public static void Main()
    {
        object obj = null;
        decimal? nullDecimal = null;

        Test(obj);         // Expected: Something else, Actual: Something else
        Test(nullDecimal); // Expected: Nullable decimal, Actual: Something else
    }

    public static void Test(object value)
    {
        if (value is decimal)
        {
            Console.WriteLine("Decimal");
            return;
        }

        if (value is decimal?)
        {
            Console.WriteLine("Nullable decimal");
            return;
        }

        Console.WriteLine("Something else");
    }
}

Is it even possible in .NET?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
  • `null` is the absence of an object, and as such also the absence of a type. You cannot check the type of something that isn’t there. – poke May 24 '16 at 13:43

1 Answers1

3

In your example it is impossible to determine whether it was an object or a decimal?. In both cases, simply a null reference is passed along, the type information is not. You can capture the type information using generics:

public static void Main()
{
    object obj = null;
    decimal? nullDecimal = null;

    Test(obj);         // prints Something else
    Test(nullDecimal); // prints Nullable decimal
}

public static void Test<T>(T value)
{
    if (typeof(T) == typeof(decimal))
    {
        Console.WriteLine("Decimal");
        return;
    }

    if (typeof(T) == typeof(decimal?))
    {
        Console.WriteLine("Nullable decimal");
        return;
    }

    Console.WriteLine("Something else");
}

With this, whether the value you pass is null or not, the compile-time type is automatically captured.

Tim S.
  • 55,448
  • 7
  • 96
  • 122