Add a Constraint to restrict a generic to numeric types


  • Hi,

    I would like to add to a generic class a constraint to restrict the generic type to numeric objects like int, double, short, etc.
    I'm not sure, whether restricting it to IComparable is enough.

    Code Block

    public class Number<NumType>  where NumType : ( .. numeric constraint .. )


    I don't know the easiest way to restrict it to a number. Basically, + - * / = operators should be supported. Adding a constraint to System.ValueType isn't possible ( and I'm not sure how that would be helping ) .

    My idea behind this is a (mostly) generic mapping class for numeric types to be mapped to double as main type with an applied scaling factor.
    The problem is, that e.g. I can't do a cast like this:

    Code Block

    // member of Number<NumType>
    ConvertToDouble(NumType Val)
    double tmp = (double)Val;
    return tmp;

    Also runtime casting doesn't works.


    I took a short look at the Convert class, which does some of the things i would like to do. But a generic approach would be more elegant, so I would really appreciate any comments on this.

    Friday, November 02, 2007 9:36 AM


All replies

  • There's no such constraint unfortunately. IComparable doesn't imply a numeric type. You can read more about the issue here

    Friday, November 02, 2007 10:47 AM
  • Hi Mattias,

    thanks for your answer. It's a very interesting link, although it shows that C# has some drawbacks in certain scenarios and is not a real equivalent for C++ yet...  or  is  something  like  this  upcoming in  the 3.5 version ?

    Friday, November 02, 2007 10:55 AM
  • Hi Florian,


    As far as I know, there is no straightforward support for generic types calculations in .NET 3.5 version. If you would like to do so, try to refer to mattias's suggestions. Thanks.


    Hope this helps,


    Monday, November 05, 2007 8:38 AM
  •  Florian Storck wrote:
    C# has some drawbacks in certain scenarios and is not a real equivalent for C++ yet...

    C# will NEVER be a real equivalent for C++. It will always have some major differences, for example C# has garbage collection and non-deterministic destructors. That's hugely different from C++.
    Monday, November 05, 2007 10:26 AM
  • Hello Matthew,

    I meant "equivalent" rather in comparison of language semantics, not in the generated code and memory model. And there are major lacks when you look at the Generics compared with C++ Templates, which I think are not induced by the Garbage Collection. But you're right, if it comes to coding on the metal, C# can't be a replacement for C++.


    Friday, November 09, 2007 11:02 AM