There are some tricks to enforce a generic class to work only with numeric types (see this)
I am creating a library where I end up writing where T : struct, IComparable ...
in many class definitions. I want to create an empty interface like this:
public interface INumeric<T>
where T :
struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T> { }
and then implement that interface in my generic class:
public struct StepSize<T> : INumeric<T>
but when I try to compare a number with
if (value.CompareTo(default(T)) <= 0)
I get the error:
'T' does not contain a definition for 'CompareTo' ...
Why am I getting the error? I am restricting T
's type in the interface already, so T
must be IComparable
.
EDIT: here the two classes
namespace NumericalAlgorithms
{
using System;
public interface INumeric<T>
where T :
struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>
{ }
}
and
namespace NumericalAlgorithms.NumericalMethods
{
using System;
public struct StepSize<T> : INumeric<T>
{
public T Value
{
get;
private set;
}
public StepSize(T value)
: this()
{
if (value.CompareTo(default(T)) <= 0)
throw new Exception("The step size must be greater than zero.");
this.Value = value;
}
}
}