470,874 Members | 1,859 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,874 developers. It's quick & easy.

Using math operator with generics

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
2 12882
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
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.

Similar topics

1 post views Thread by praba kar | last post: by
5 posts views Thread by William Gill | last post: by
14 posts views Thread by Tony Johansson | last post: by
1 post views Thread by Pawel | last post: by
94 posts views Thread by krypto.wizard | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.