I have a class:
public interface IA
{
TValue? GetValue<TValue>();
}
public class A : IA
{
public TValue? GetValue<TValue>()
{
...
if (value is not null)
return (TValue)value;
return default(TValue);
}
}
This is alright, but when I try to implement the interface explicitly:
public interface IA
{
TValue? GetValue<TValue>();
}
public class A : IA
{
TValue? IA.GetValue<TValue>()
{
...
if (value is not null)
return (TValue)value;
return default(TValue);
}
}
The compiler throws an error:
Cannot implicitly convert type TValue to TValue?
Is there a difference when implementing an interface explicitly? This seems to only be the case when dealing with a nullable generic return type.
Is this a bug or am I missing something?
You need to use default constraint:
TValue? IA.GetValue<TValue>() where TValue : default
To allow annotations for type parameters that are not constrained to reference types or value types