Search code examples
c#.netnullnullable

How to distinct between (object)null and (decimal?)null when passed in object parameter?


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?


Solution

  • 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.