By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,493 Members | 1,250 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,493 IT Pros & Developers. It's quick & easy.

Using math operator with generics

P: n/a
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.
Nov 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Mon, 17 Oct 2005 10:55:57 +0200, Marco Segurini
<ma***********@virgilio.it> wrote:
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.
--
http://www.kynosarges.de
Nov 17 '05 #2

P: n/a
On Mon, 17 Oct 2005 10:55:57 +0200, Marco Segurini
<ma***********@virgilio.it> wrote:

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

--
Marcus Andrén
Nov 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.