473,769 Members | 7,375 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics And Arithmetic

Hi,

When I do the following

public class IAmAGeneric<T>
{
...
public T AMember (T a, T b) { return a + b; };
}

C# complains that

operator '+' cannot be applied to operands of type 'T' and 'T'

I haven't found any documentation that says this won't work but
I haven't found any that says it will. Nor an example. Is this a
limitation of C# generics? Is there a workaround?

This usage is common in C++ templates. Is this limitation because
C++ templates are like macros and C# generics are like classes
(according to the C# head honcho).

Thanks,
Gary
Aug 14 '06 #1
8 2554
Gary Brown wrote:
When I do the following

public class IAmAGeneric<T>
{
...
public T AMember (T a, T b) { return a + b; };
}

C# complains that

operator '+' cannot be applied to operands of type 'T' and 'T'
If you try and instantiate your class above as IAmAGeneric<int >, I bet it'll work. However, if you use types that don't have the '+' operator overloaded, then of course it won't.

--
Torben K. Jensen
Aug 14 '06 #2
Gary Brown wrote:
Hi,

When I do the following

public class IAmAGeneric<T>
{
...
public T AMember (T a, T b) { return a + b; };
}

C# complains that

operator '+' cannot be applied to operands of type 'T' and 'T'

I haven't found any documentation that says this won't work but
I haven't found any that says it will. Nor an example. Is this a
limitation of C# generics? Is there a workaround?
Within a generic method, you can only call methods that are known to be
valid for the generic type(s). With a plain generic, like you've shown
here, that means you can only call the members of System.Object, since those
are the only members known to be valid for any T.

So, you ask, how do you do something more interesting? With constraints:

public class IAmAGeneric<Twh ere T : ISomeInterface
{
}

Sadly, there's no interface that includes overloaded operator +, so there's
no way you can actually write a+b where a & b are typed by a generic type
parameter.

See here:

http://msdn2.microsoft.com/en-us/library/d5x73970.aspx

for more details.
>
This usage is common in C++ templates. Is this limitation because
C++ templates are like macros and C# generics are like classes
(according to the C# head honcho).
..NET generics are not C++ templates. They have their strengths and their
weaknesses compared to C++ templates. This is one of their big weaknesses
(and is a consequence of one of their big strengths).

-cd
Aug 14 '06 #3
I stand corrected (now that I've tried your code).

Here's a possible solution:
public abstract class PlusOp {

public static PlusOp operator +(PlusOp first, PlusOp second) {
return first.AddTo(sec ond);
}

public abstract PlusOp AddTo(PlusOp value);
}

public class IAmAGeneric<Twh ere T : PlusOp {

public T AMember(T a, T b) {
return (T)(a + b);
}
}
Hope that helps.
--
Torben K. Jensen
Aug 14 '06 #4
Gary Brown wrote:
When I do the following

public class IAmAGeneric<T>
{
...
public T AMember (T a, T b) { return a + b; };
}

C# complains that

operator '+' cannot be applied to operands of type 'T' and 'T'

I haven't found any documentation that says this won't work but
I haven't found any that says it will. Nor an example. Is this a
limitation of C# generics? Is there a workaround?

This usage is common in C++ templates. Is this limitation because
C++ templates are like macros and C# generics are like classes
(according to the C# head honcho).
As other have already explained then the usage of T is
type checked.

The C# generics model is simply significantly
different from the C++ template model.

If you want to see some of the weird stuff people
has been doing for workarounds then check:

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

Arne
Aug 14 '06 #5
Gary Brown wrote:
Hi,

When I do the following

public class IAmAGeneric<T>
{
...
public T AMember (T a, T b) { return a + b; };
}

C# complains that

operator '+' cannot be applied to operands of type 'T' and 'T'

I haven't found any documentation that says this won't work but
I haven't found any that says it will. Nor an example. Is this a
limitation of C# generics? Is there a workaround?

This usage is common in C++ templates. Is this limitation because
C++ templates are like macros and C# generics are like classes
(according to the C# head honcho).

Thanks,
Gary
Hi Gary,

The compiler is correct, + cannot be applied to operands of those type,
because the + operator may not be defined for the type specified in the
generic parameter, for example, the + operator is defined for 'int' but not
for 'ListViewItem'.

So, if I had an 'IAmAGeneric<Li stViewItem>' the + operator would not be
valid. The compiler knows this, and so won't compile if there's the
possibility of a type mismatch.

--
Hope this helps,
Tom Spink

Google first, ask later.
Aug 14 '06 #6
Thanks for the responses.

Some of the articles pointed to imply this restriction is temporary
until Whidbey. Is this true? And when and what is Whidbey (other
than an island)?

Gary
Aug 15 '06 #7
Hi,

"Gary Brown" <ga********@cha rter.netwrote in message
news:Ol******** ********@TK2MSF TNGP03.phx.gbl. ..
Thanks for the responses.

Some of the articles pointed to imply this restriction is temporary
until Whidbey. Is this true? And when and what is Whidbey (other
than an island)?
Whidbey was the codename for VS 2005 , so you are using it already :)

IMO this restriction will be permanent, unless that another mechanism is
introduced.

A possible workaround though is using reflection. You may be able to call
the "+" operation using reflection.

--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Aug 15 '06 #8
If only for a few more core interfaces... perhaps something like:

// e.g. most numeric types, plus other structures - matrices etc
//(undefind methods per type could always throw NotSupportedExc eption)
public interface IArithmetic<T: IEquatable<T{
// not IComparable<T>, as not always sequenced?
// callers could always insist IComparable<Tse parately
T Add(T value);
T Subtract(T value);
T DivideBy(T value);
T MultiplyBy(T value);
// needed to support many core math functions; shame
// no static interface memebers...
T One { get;}
T Zero { get;}
}
// e.g. int, long, uint, ulong, enums (although enums don't currently
support IEquatable<them selves>)
public interface ILogical<T: IEquatable<T{
// not sure should be shiftable, as
// doesn't make much sense for enums etc
T Or(T value);
T And(T value);
T Not();
T Xor(T value);
// ditto static members
T None { get;}
T All { get;}
}

Then afterwards I googled it and found the following, which is alarmingly
similar (for IArithmetic<T>) - convergence?...

http://www.lambda-computing.com/publ...cles/generics/

Marc
Aug 17 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
2462
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and still no can do... Any info would be great!
23
2552
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics vs C++ templates. Does anyone knows a workaround to do this ? Thx : public class C<T> { private T myValue;
12
2744
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as it defines the language more completely. Great to use.
2
1334
by: Herby | last post by:
I need to define my own types and arrays of these types. These types are for the most part extensions of the built in types and need to provide all the basic operations of arithmetic and relational. If i was using C++ I would overload the operators against my types and use STL Vector etc. No problem. No performance costs. No virtual functions, no casting etc.
9
5986
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
1
2438
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes "ThrowInConstructor" and "ThrowInFoo". First one throws "MyOwnException" in constructor, second one in "Foo()" method. There is a "GenericCatch" generics class able to accept "ThrowInConstructor" and "ThrowInFoo" as type parameter "<T>". There are two methods in...
13
3837
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The problem I'm running into has to do with the differences in implementations of Generics between the two...
6
1183
by: Matteo Migliore | last post by:
Hi. I want to costraint a generics T to be a number (Int32, Double, Byte etc...) but how I can do? I need beacuse I want to use arithmetic operators (+, -...). Thx! ;-)
17
1905
by: My interest | last post by:
How can I use * operator in C# generics? e.g. class foo<T_> { T_ v1, v2: public T_ squar() { return v1 * v2; /// wrong! }
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5309
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.