Home > Net >  Can we use a null instance of a class with a generic-typed property without declaring the Type of th
Can we use a null instance of a class with a generic-typed property without declaring the Type of th

Time:07-27

If a class has a property that is of a generic type (Like Thingus<T> below), is it possible to use a null instance of that class without specifying the type of the generically-typed property for that object?

using System;
                    
public class Program
{
    public static void Main()
    {
        DoThing(new Thingus<int>
        {
            Name = "Integer thingus",
            Something = 42
        });
        
        //Is there a way to make this function work without the function on line 19?
        //If thingus is null then I don't care what the Type is for Something.
        //If not, does the type used in the function on line 19 matter for performance at all?
        DoThing();
    }
    
    public static void DoThing(Thingus<string> thingus = null) => DoThing<string>(thingus);
    
    public static void DoThing<T>(Thingus<T> thingus)
    {
        if(thingus is null)
        {
            Console.WriteLine("Oh look! The thingus is null!");
        }
        else
        {
            Console.WriteLine($"Thingus's Something is {thingus.Something}");
        }
    }
}

public class Thingus<T>
{
    public string Name { get; set; }
    public T Something { get; set; }
}

CodePudding user response:

You don't need to specify the type parameter on your first call, because the compiler can infer it from the int on the type parameter in the argument. In your second method, it can't infer that, because you want to send null.

You can drop the method you want to drop, and call your generic method with some irrelevant type parameter to satisfy the compiler:

DoThing<Thingus<int>>(null);

CodePudding user response:

To see why it is probably impossible, consider this code snippet

public static void DoThing<T>(Thingus<T> thingus)
{
    Console.WriteLine(typeof(T));
}

If you write DoThing(null), there is no hints that which type T you want to use, so it is impossible for the compiler to make it works because with just DoThing(null) you are providing not enough information for the compiler.

  • Related