3

I’d like to declare a generic class Simple where a method called Addition would take two generic variables and add them together using + operator. I thought I could accomplish this by giving class Simple the following constraint:

class Simple<T> where T: int
{
    public T Addition(T firstInt, T secondInt)
    {
        return firstInt + secondInt;
    }
}

I suspect error has something to do with generics only having the following five types of constraints - ClassName, class, struct,InterfaceName, new()? Thus, why don’t generics also support StructureName constraint type? That way we would be able to apply arithmetic operators on generic variables?!

thanx

AspOnMyNet
  • 1,958
  • 4
  • 22
  • 39

3 Answers3

4

A StructName constraint wouldn't make sense, since you cannot inherit from value types.

If you had something like class Simple<T> where T : int you could only instantiate Simple<T> with T = int, no type inherits from int or any other value type for that matter.

C# (the CLR) lacks what other languages know as type classes, one popular mechanism to handle operator overloading without hard-coded compiler mechanics (like in C#).

Christian Klauser
  • 4,416
  • 3
  • 31
  • 42
2

There is no point in constraining a Generic type to a specific struct, since struct types cannot be inherited. This would be identical to writing:

class Simple
{
    public int Addition(int firstInt, int secondInt)
    {
        return firstInt + secondInt;
    }
}

Unfortunately, with support for an IArithmetic interface, generic types with mathematical operations are difficult to support. If you want to see one approach for generic-based mathmetical operators, look to the Generic Operators in MiscUtil.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

You constrain T to int. This is no sensible thing to do, as there is only one int type; so you could directly want to write int if you want int.

If you do not constrain T, you cannot use the + operator, since there is no + operator defined on object.

C# generics are not C++ templates.

David Schmitt
  • 58,259
  • 26
  • 121
  • 165