Trying to make Feature
generic and then suddenly compiler said
Operator '?' cannot be applied to operand of type 'T'
Here is the code
public abstract class Feature<T>
{
public T Value
{
get { return GetValue?.Invoke(); } // here is error
set { SetValue?.Invoke(value); }
}
public Func<T> GetValue { get; set; }
public Action<T> SetValue { get; set; }
}
It is possible to use this code instead
get
{
if (GetValue != null)
return GetValue();
return default(T);
}
But I am wondering how to fix that nice C# 6.0 one-liner.
where T : class
are missing the fact that you're checking if theFunc<T>
is null not aT
, as your second block of code shows. If that works then theGetValue?.Invoke()
syntax should work also. You should be able to write:return GetValue?.Invoke() ?? default(T)
– Sannyasi?.
returningnull
if the expression wasnull
, and notdefault(T)
. – ChronopherAction<T>
while thats nullable too. the cause is something else. and i dont think its a bug. and my guess is because Action return type is void but Func returns T. @Sannyasi – HelixGetValue?.Invoke()
. IfT
isclass
orNullable<>
, than result type should beT
, but ifT
isstruct
, than result type should beT?
. – Remunerateint
such as fromList?.Count
which you can solve by using??
such asList?.Count ?? 0
. – SannyasiList?.Count
isint?
. It is know at compile time, that type should be promoted to nullable. Result type ofGetValue?.Invoke()
isT
orT?
. It is not know at compile time, should type be promoted to nullable, or it nullable already. – Remunerate