Reed
Reed

Reputation: 1642

Method that accepts generic argument as null

I want to write a method like this. However, the language does not like the T obj = null in the method arguments. And it does not like the obj == null either. I have tried T : object T : INullable to no avail. Is there any way I can get C# to accept this?

    public virtual static async Task<T> Get<T>(T obj = null) where T : struct
    {
        if (obj == null)
        {
            // Do stuff
        }
        else
        {
            // Do other stuff
        }
    }

Upvotes: 1

Views: 84

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23288

To use null value as default one you should apply where T : class generic constraint. Or even use Get<T>(T obj = default) without constraints (if default literal and C# 7.1 is available).

If you still need a T as value type (and struct constaint), just declare method as Get<T>(T? obj = null) where T : struct. T? in this case means Nullable<T> struct

Upvotes: 5

Related Questions