473,385 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 2529
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<Twhere 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(second);
}

public abstract PlusOp AddTo(PlusOp value);
}

public class IAmAGeneric<Twhere 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<ListViewItem>' 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********@charter.netwrote in message
news:Ol****************@TK2MSFTNGP03.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 NotSupportedException)
public interface IArithmetic<T: IEquatable<T{
// not IComparable<T>, as not always sequenced?
// callers could always insist IComparable<Tseparately
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<themselves>)
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
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...
23
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...
12
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...
2
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...
9
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...
1
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...
13
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...
6
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
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.