473,397 Members | 2,056 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,397 software developers and data experts.

Generics, use +/-/* operator etc

How can I use * operator in C# generics? e.g.

class foo<T_>
{
T_ v1, v2:

public T_ squar()
{
return v1 * v2; /// wrong!
}
}

Dec 14 '07 #1
17 1873
On Fri, 14 Dec 2007 11:25:27 -0800, My interest <my********@gmail.com>
wrote:
How can I use * operator in C# generics? e.g.

class foo<T_>
{
T_ v1, v2:

public T_ squar()
{
return v1 * v2; /// wrong!
}
}
I don't think you can. To use the * operator (or any operator, for that
matter), the compiler has to know that you're dealing with types that have
a defined overload for the operator.

If you have a situation where you can constrain your generic type
parameter to one that does have a valid operator* overload, then that
would work. But without any other information from you, it seems likely
that you're looking to get this behavior with value types and of course
they don't have any inheritance relationship that would allow you to
define a useful constraint like that.

I suppose you could define overloads within your class, covering all the
types you want to handle. I haven't tried it myself, but hopefully the
compiler would be able to pick the right overload at compile time. For
example:

class foo<T_>
{
T_ v1, v2;

public static T_ squar(int t1, int t2)
{
return (T_)(t1 * t2);
}

public static T_ squar(float t1, float t2)
{
return (T_)(t1 * t2);
}

// etc.

public T_ squar()
{
return squar(v1, v2);
}
}

Actually, seeing that in code, I'm not so sure. The compiler might sitll
find something to complain about. But it's worth a try anyway.

Pete
Dec 14 '07 #2

"My interest" <my********@gmail.comwrote in message
news:53**********************************@b40g2000 prf.googlegroups.com...
How can I use * operator in C# generics? e.g.

class foo<T_>
{
T_ v1, v2:

public T_ squar()
{
return v1 * v2; /// wrong!
}
}
It's a well known problem -- you can't.

Search codeproject for "C# generic arithmetic" for workarounds.

Dec 14 '07 #3
My interest <my********@gmail.comwrote:
How can I use * operator in C# generics? e.g.

class foo<T_>
{
T_ v1, v2:

public T_ squar()
{
return v1 * v2; /// wrong!
}
}
You can't, properly - it's been the cause of a fair amount of work.

However, if you're using .NET 3.5 Marc Gravell has a very cunning way
of doing it with expression trees, which I plan to blog about at some
point...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Dec 14 '07 #4

"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Fri, 14 Dec 2007 11:25:27 -0800, My interest <my********@gmail.com>
wrote:
>How can I use * operator in C# generics? e.g.

class foo<T_>
{
T_ v1, v2:

public T_ squar()
{
return v1 * v2; /// wrong!
}
}

I don't think you can. To use the * operator (or any operator, for that
matter), the compiler has to know that you're dealing with types that have
a defined overload for the operator.

If you have a situation where you can constrain your generic type
parameter to one that does have a valid operator* overload, then that
would work. But without any other information from you, it seems likely
that you're looking to get this behavior with value types and of course
they don't have any inheritance relationship that would allow you to
define a useful constraint like that.

I suppose you could define overloads within your class, covering all the
types you want to handle. I haven't tried it myself, but hopefully the
compiler would be able to pick the right overload at compile time. For
example:

class foo<T_>
{
T_ v1, v2;

public static T_ squar(int t1, int t2)
{
return (T_)(t1 * t2);
}

public static T_ squar(float t1, float t2)
{
return (T_)(t1 * t2);
}

// etc.

public T_ squar()
{
return squar(v1, v2);
}
}

Actually, seeing that in code, I'm not so sure. The compiler might sitll
find something to complain about. But it's worth a try anyway.
No, overload resolution in generics is done based on the constraints only,
not the final type. This is what lets generics be exported in MSIL form, as
opposed to C++ templates which do overload resolution for each actual
combination of type parameters but can only be shared in source form.

In the above code, you'd get an error on each return statement because the
compiler doesn't know how to cast int to T_, nor float to T_, and another
trying to resolve which squar function is being used, because the only
guarantee is that v1 and v2 derive from T_ and object, but there are no
functions accepting parameters of either T_ or object.
>
Pete
Dec 14 '07 #5
On Fri, 14 Dec 2007 11:59:03 -0800, Ben Voigt [C++ MVP]
<rb*@nospam.nospamwrote:
[...]
No, overload resolution in generics is done based on the constraints
only, not the final type. This is what lets generics be exported in
MSIL form, as opposed to C++ templates which do overload resolution for
each actual combination of type parameters but can only be shared in
source form.
Oh well, it was worth a try. :) I'm a bit confused though: I thought
that for value types, a new instance of the class was generated for each
variation of the generic class.

In other words, while I do expect the problem you're describing with
reference types, I thought there was a chance that the compiler would
resolve things early enough for value types that the overloading and
casting would be okay.

Of course, if I'd tried to compile it I'd know for sure. I'm not
questioning what you're saying, just trying to figure out why, if value
types are handled differently anyway, they aren't a work-around for this
problem.

Pete
Dec 14 '07 #6
Peter Duniho <Np*********@nnowslpianmk.comwrote:
[...]
No, overload resolution in generics is done based on the constraints
only, not the final type. This is what lets generics be exported in
MSIL form, as opposed to C++ templates which do overload resolution for
each actual combination of type parameters but can only be shared in
source form.

Oh well, it was worth a try. :) I'm a bit confused though: I thought
that for value types, a new instance of the class was generated for each
variation of the generic class.
The JIT will spit out new native code for each value type, but the
compiler keeps it in a single generic type.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Dec 14 '07 #7
I'm not questioning what you're saying, just trying to figure out why, if value
types are handled differently anyway, they aren't a work-around for this
problem.
For info, for people using . NET 3.5 I have a usable solution for
this. It doesn't (unfortunately) offer compile-time checking, but it
provides very efficient access to all the common operators. Quick
enough to be directly comparable to regular compiled code.

Let me know if people are interested...

Marc
Dec 14 '07 #8
Marc Gravell <ma**********@gmail.comwrote:
I'm not questioning what you're saying, just trying to figure out why, if value
types are handled differently anyway, they aren't a work-around for this
problem.

For info, for people using . NET 3.5 I have a usable solution for
this. It doesn't (unfortunately) offer compile-time checking, but it
provides very efficient access to all the common operators. Quick
enough to be directly comparable to regular compiled code.
In explaining it to a friend, I think the easiest way of thinking about
them is as "duck-typed operators" :)

(I hasten to add that while I understand the principle of the thing, I
don't understand Marc's code... :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Dec 14 '07 #9
I've wondered this for a while now, and maybe the reasoning is blatantly
obvious and I'm a fool or it's been asked and answered before, but is
there a reason why the numeric types don't implement an interface that
defined the operators for math as required?

At least then we could use a generic constraint (amongst other things)
for issues like this.

Chris.
Dec 14 '07 #10
(I hasten to add that while I understand the principle of the thing, I
don't understand Marc's code... :)
For the group's benefit - that doesn't mean that it is hard to use -
consider the following, for example, that works for *any* type that
declares a suitable add operator (even your own bespoke
"ComplexInt32"). If it can't find the operator it will throw an
InvalidOperationException at runtime - but it will run almost as
quickly as a specific overload implementation:

public static T Sum<T>(this IEnumerable<Tsource)
{
if (source == null) throw new ArgumentNullException();
T sum = Operator<T>.Zero; // not the same as default(T);
think "int?"
foreach (T value in source)
{
if (value != null)
{ // ignore nulls (think "int?"; recall 0 + null =
null)
sum = Operator.Add(sum, value);
}
}
return sum;
}
Dec 14 '07 #11
On Fri, 14 Dec 2007 13:07:11 -0800, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
>Oh well, it was worth a try. :) I'm a bit confused though: I thought
that for value types, a new instance of the class was generated for each
variation of the generic class.

The JIT will spit out new native code for each value type, but the
compiler keeps it in a single generic type.
Ahh...I thought it was the C# compiler doing that work. Okay then...I can
see how if the C# compiler always keeps a single generic type, why it then
has the limitations Ben describes. Thanks!

Pete
Dec 14 '07 #12
Chris Shepherd <ch**@nospam.chsh.cawrote:
I've wondered this for a while now, and maybe the reasoning is blatantly
obvious and I'm a fool or it's been asked and answered before, but is
there a reason why the numeric types don't implement an interface that
defined the operators for math as required?

At least then we could use a generic constraint (amongst other things)
for issues like this.
Aside from anything else, operators are static, so can't be part of an
interface implementation.

I think with a big change to a lot of stuff it would be possible, but
MS hasn't got round to it yet...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Dec 14 '07 #13
Marc Gravell <ma**********@gmail.comwrote:
(I hasten to add that while I understand the principle of the thing, I
don't understand Marc's code... :)

For the group's benefit - that doesn't mean that it is hard to use
Sorry, yes, I should have made that clear. It's incredibly easy to use
- the implementation is just slightly confusing, due to being in
expression trees, which are fundamentally hard to get your head round
(well, so I find).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Dec 14 '07 #14
is there a reason why the numeric types don't implement an interface that
defined the operators for math as required?
A number of such have been proposed (as discussion points on forums
like this), but they all suffer from the fact that our current
understanding of operators is much more flexible than a standard
interface would permit. Often there are operators against a range of
different types with different outputs, so the signatures of the
methods would be tricky - it isn't always T with "T Operator(T arg)".

The nature of maths is an issue too - the operations supported by
different number systems are not consistent; "uint", for instance,
doesn't define "negate" (additive inverse). Likewise the int-based
numbers don't define "reciprocol" (multiplicative inverse), nor do non-
square matrices. Division is better supported, but still has issues.
This means that either you'd have a ridiculous number of (probably
generic) interfaces (with 1, maybe 2 methods each), or you'd have a
few interfaces (with lots of simple T=>T methods) where you already
know that some methods are reasonably likely to throw "NotSupported"
or "InvalidOperation" (because they simply don't make sense for that
number system).
The first option (lots of interfaces) becomes very restrictive and
almost impossible to use; the second (untrustworthy interfaces)
doesn't buy an awful lot of *true* safety anyway.

Thus I propose that the duck-typing (to borrow Jon's usage) is
certainly no worse than anything else we can currently propose; but it
works, exists today, and is as quick as you'd like.

For completeness, I have also seen a previous reply on this subject
that the number of interfaces, members, virtcalls, etc (against the
primatives) would have a significant impact on things like CF. I don't
know about the truth of this claim, however.

Marc
Dec 14 '07 #15
Is there anyway to use Reflection to invoke operator + alike? I
tried, but failed to make it work.
Dec 15 '07 #16
There is, but only for some types. IIRC, float, int etc don't provide
these as operators - they have direct IL calls. As such, you'd
probably need to use some surrogate methods for the special cases, and
look for op_Add (or whatever it is called) for the others.

This complexity is part of what my code attempts to avoid (albeit with
its own complexities ;-p).

Lutz Roeder's .NET Reflector will easily show you which operators
exist for which primatives.

Marc
Dec 15 '07 #17
Also - you'd need to be aware that "lifted operators" (for
Nullable<T>) are a compiler feature, not a runitme feature (IIRC) -
hence they don't exist for "decimal?" etc. So you'd need a whole other
arm of special handling to cope with Nullable<T>. In short, it starts
to get really messy really quickly...

It can certainly be done - it just isn't as simple as it might appear
at first inspection. I'm lazy, so I didn't do it this way...

Marc
Dec 15 '07 #18

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

Similar topics

17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
10
by: Ruediger Klaehn | last post by:
Sorry about the harsh language, but I have to vent my anger to somebody who actually understands what I am talking about. Complaining to my girlfriend is not going to produce any meaningful results...
4
by: Tom Jastrzebski | last post by:
Hello everybody, Here is the problem I came across experimenting with Generics. I would like to write a class or a struct adding integer to any other, initially undefined *numeric type*. So, my...
13
by: Luc Vaillant | last post by:
I try to compare to values of generic value type T in a generic class as follow: public class C<T> where T : struct { private T value1; private T value2; C(T value1, T value2) {
11
by: herpers | last post by:
Hello, I probably don't see the obvious, but maybe you can help me out of this mess. The following is my problem: I created two classes NormDistribution and DiscDistribution. Both classes...
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...
8
by: Gary Brown | last post by:
Hi, When I do the following public class IAmAGeneric<T> { ... public T AMember (T a, T b) { return a + b; }; }
7
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
5
by: teel | last post by:
Hi there, I'm trying to apply "less than" and "more than" operators on the Generics (class template-like) type objects. Below is the code of my class representing a parameter that can be any type,...
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: 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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.