Is it possible to implement basic arithmetic (at least addition) in C# generics, like you can with C++ templates? I’ve been trying for a while to get them up and working, but C# doesn’t let you declare the same generic type multiple times, like you can with templates.
Extensive googling did not provide an answer.
EDIT: Thanks, but what I’m looking for is a way to do the arithmetic at compile time, embedding something like Church numerals in generics types. That’s why I linked the article that I did. Arithmetic in generic types, not arithmetic on instances of generic types.
Unfortunately you cannot use arithmetic operations on generic types
will not work in c#!
But you can create your own numeric types and overload the operators (arithmetic, equality and
implicit,explicit). This lets you work with them in a quite natural way. However you cannot create an inheritance hierarchy with generics. You will have to use a non generic base class or interface.I just did it with a vector type. A shortened version here:
More than 10 years have past since I answered this question and finally the C# 11 feature – static virtual members in interfaces was introduced in .NET 7 allowing us to do Generic math and many other things.
Interfaces can now declare static factory methods not limiting us to use parameter-less constructors in generic contexts.