In the following class:
public class Example<T> where T : IComparable {
private T _min;
private T _max;
public Example() {
// _min = T.MinValue;
// _max = T.MaxValue;
}
public Example(T min, T max) {
_min = min;
_max = max;
}
public bool Contains(T val) {
return (val.CompareTo(_min) < 0) && (val.CompareTo(_max) > 0);
}
}
What would be the best way to initialize the members to their type-specific min & max values in the default constructor? I know this puts another constraint on the allowed types for the generic, but that's fine for my purposes.
Additionally, if a type supported infinite values, such as float or double, is there a way to detect this and set the values accordingly?
There's no constraint that would allow you to do get a MinValue and MaxValue. The only value you can get in a strong-typed way is the default (default(T)).
If you know that the types will have static MinValue and MaxValue properties, you can get at these using Reflection, but could not enforce the safety of this at compile time.
An alternative solution would be to redesign your class slightly: add _isMinSpecified and _isMaxSpecified boolean members, and consult these in your Contains method -- e.g. if neither a min nor a max had been specified, you would always return true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With