Operator '??' cannot be applied to operands of type 'T' and 'T'

前端 未结 8 737
旧巷少年郎
旧巷少年郎 2021-02-06 20:34

I have the following generic method, but VS gives me a compile error on that. (Operator \'??\' cannot be applied to operands of type \'T\' and \'T\')

public stat         


        
8条回答
  •  日久生厌
    2021-02-06 21:14

    You should add class constraint:

    public static T Method(T model) where T : class, new()
    {
        var m = model ?? new T();
    
        return m;
    }
    

    And you should return m too!

    Note: As @KristofDegrave mentioned in his comment, the reason that we have to add class constraint is because T can be a value type, like int and since ?? operator (null-coalescing) check on types that can be null, so we have to add class constraint to exclude value types.

    Edit: Alvin Wong's answer covered the case for nullable types too; which are structs actually, but can be operands of ?? operator. Just be aware that Method would return null without Alvin's overloaded version, for nullable types.

提交回复
热议问题