Pygmy Pygmy - 1 month ago 4x
C# Question

C# Generics : how to use x.MaxValue / x.MinValue (int, float, double) in a generic class

I'm using the WPF Extended Toolkit ( ).

It has a nice NumericUpDown control that I'd like to use, but internally it uses doubles - which means it uses double.MinValue and double.MaxValue.

I'd like to use the same control, but I need a generic version - for ints it needs to use int.MaxValue/MinValue, for floats float.MaxValue/MinValue, etc. (I think you get the idea :))

So I though about copying the NumericUpDown to a GNumericUpDown, where T would ofcourse be the Type..
But this doesn't work, because a generic Type doesn't have MinValue / MaxValue.
And normally I'd use the 'where' clause to specify a base-type, but this doesn't work as afaik there's no common interface that defines 'MinValue' and 'MaxValue'.

Is there a way to solve this with generics, or do I really need to copy/paste/search&replace the original NumericUpDown for each type ?


The OP made this comment on another answer:

I want to use these controls in my XAML. My idea was to create a generic version, and then create empty classes like NumericUpDownInt : GNumericUpDown { } Would that be the way to go, or is there a better/cleaner way to your knowledge

If you're going to go that route, then just pass the min and max directly:

class abstract GenericNumericUpDown<T>
    public GenericNumericUpDown(T min, T max) { ... }

class NumericUpDownInt : GenericNumericUpDown<int>
    public NumericUpDownInt() : base(int.MinValue, int.MaxValue) { ... }

class NumericUpDownFloat : GenericNumericUpDown<float>
    public NumericUpDownFloat() : base(float.MinValue, float.MaxValue) { ... }

class NumericUpDownDouble : GenericNumericUpDown<double>
    public NumericUpDownDouble() : base(double.MinValue, double.MaxValue) { ... }