Using math operator with generics

M

Marco Segurini

Hi,

The following code shows my problem:

using System;
using System.Collections.Generic;
using System.Text;

....

namespace ConsoleApplication1
{
static class MyOp
{
public static T Sub<T>(T item1, T item2)
where T : struct
{
return item1-item2; // this is line 118
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyOp.Sub(2,3));
}
}
}

Build result:
Program.cs(118,17): error CS0019: Operator '-' cannot be applied to
operands of type 'T' and 'T'

What have I to add to 'where' to tell to the generic function that T
implements operator- ?

Another question: the C# built-in types (byte,int,double,...) have
associated the same set of operation {+,-,*,/}: are these types derived
from common interface?

TIA.
Marco.
 
C

Christoph Nahr

What have I to add to 'where' to tell to the generic function that T
implements operator- ?

You can't do that. There is no operator constraint in C# 2.0.
Another question: the C# built-in types (byte,int,double,...) have
associated the same set of operation {+,-,*,/}: are these types derived
from common interface?

They are not. There have been a few threads on this subject before,
and the conclusion was that it is impossible to perform any of the
built-in mathematical operations on generic types.

If you want to write a class that works on different numeric types you
have to it the old-fashioned way -- provide strongly-typed overloads
for each version. Generics are no help here, unfortunately.
 
M

Marcus Andrén

What have I to add to 'where' to tell to the generic function that T
implements operator- ?

Another question: the C# built-in types (byte,int,double,...) have
associated the same set of operation {+,-,*,/}: are these types derived
from common interface?

Unfortunally operators can't belong to interfaces so there is no
direct way of doing it. If you still want/need it, there is an
excellent article that describes how to work around the problem. It
can be found at

http://www.codeproject.com/csharp/genericnumerics.asp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top