473,770 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1905
On Fri, 14 Dec 2007 11:25:27 -0800, My interest <my********@gma il.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********@gma il.comwrote in message
news:53******** *************** ***********@b40 g2000prf.google groups.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********@gma il.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.co m>
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*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Fri, 14 Dec 2007 11:25:27 -0800, My interest <my********@gma il.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.nos pamwrote:
[...]
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*********@nn owslpianmk.comw rote:
[...]
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.co m>
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**********@g mail.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.co m>
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

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

Similar topics

17
3328
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 way they are. ***** Summary & Questions ***** In a nutshell, the current .NET generics & .NET framework make it sometimes difficult or even impossible to write truly generic code. For example, it seems to be impossible to write a truly generic
10
2605
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 other than straining our relationship... I just downloaded Visual C# Express Edition to mess with .NET 2.0 generics. Being a numerically inclined developer, the first thing I wanted to write was a generic complex number class. I also have some...
4
391
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 struct would look more or less like: struct MySum<T> where T : struct { public static T AddInteger(T value, int i) { return value + i;
13
1697
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
2501
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 provide an implemation of the operator +. Now I want to write another generic class Plan<DType>, which can
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. ...
8
2555
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
2214
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
2243
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, but only if it's float or int the comparison results in true/false-like result, else its INVALID. I get error: Operator '<' cannot be applied to operands of type 'T' and 'T' at line: set { m_Value = value < m_MinValue ? m_MinValue : (value >...
0
9618
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
9454
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10260
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10101
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...
1
7456
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
5354
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.