I've read several of the other questions on the topic of nullable types in generics and I still don't understand why MinMaxBase<T> and MyIntDecl compile and YourIntDecl doesn't.
The compiler error is:
'YourIntDecl' does not implement interface member 'IMinMaxDecl.MinValue'. 'YourIntDecl.MinValue' cannot implement 'IMinMaxDecl.MinValue' because it does not have the matching return type of 'short'.
Without the IComparable constraint public class YourIntDecl : IMinMaxDecl<Int16?> compiles (notice the nullable Int16 type param), but with the constraint I get this error:
The type 'short?' cannot be used as type parameter 'T' in the generic type or method 'IMinMaxDecl'. The nullable type 'short?' does not satisfy the constraint of 'System.IComparable'. Nullable types can not satisfy any interface constraints.
What is the correct solution if I can't inherit from MinMaxBase because I need to have another base class?
public interface IMinMaxDecl<T> where T : IComparable
{
T? MinValue { get; set; } // needs to be nullable because it is optional
T? MaxValue { get; set; } // needs to be nullable because it is optional
}
public abstract class MinMaxBase<T> : IMinMaxDecl<T> where T : IComparable
{
public T? MinValue { get; set; }
public T? MaxValue { get; set; }
}
public class MyIntDecl : MinMaxBase<Int16>; // compiles fine
public class YourIntDecl : IMinMaxDecl<Int16>
{
public Int16? MinValue { get; set; }
public Int16? MaxValue { get; set; }
}
MinMaxBase, you are still not getting what you'd expect -> test whetherMyIntDecl.MinValueisInt16?-> it's not. It'sInt16MinValueandMaxValueneed to be optional? Just don't implement the interface if you don't have a min / max. But the actual problem is thatT?means different things to classes and structures. If you don't specifyclass/structin yourwherethen it behaves as if it is a class. see learn.microsoft.com/en-us/dotnet/csharp/programming-guide/…