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