I have the following code and I want to pass the MinValue and MaxValue of a generic type. It would also help to somehow be able to specify that the generic type should have the MinValue and MaxValue properties via interfaces but I cannot not find the right interface.
public class TreeNode<T> where T : IComparable
{
public T data { get; set; }
public TreeNode(T value) {...}
public bool IsValidBST()
{
return IsValidBST(this, T.MinValue, T.MaxValue);
}
public bool IsValidBST(TreeNode<T> node, T min, T max) {...}
}
But my compiler tells me that "T is a type parameter which is not valid in the given context".
As of early 2022, this functionality is currently in preview in .NET 6, under the work being done on generic math. The interface in question is IMinMaxValue<TSelf>:
public class TreeNode<T> where T : IMinMaxValue<T>
{
// ...
public bool IsValidBST()
{
return IsValidBST(this, T.MinValue, T.MaxValue);
}
}
However, static abstract members, which let you access e.g. T.MinValue on some generic type T, are not currently available unless you opt into these preview features (see the blog post above for instructions on how to do this).
If you don't want to opt into preview features, there is no built-in functionality to do what you need.