473,785 Members | 2,440 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
17 1908
(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
InvalidOperatio nException at runtime - but it will run almost as
quickly as a specific overload implementation:

public static T Sum<T>(this IEnumerable<Tso urce)
{
if (source == null) throw new ArgumentNullExc eption();
T sum = Operator<T>.Zer o; // 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(su m, value);
}
}
return sum;
}
Dec 14 '07 #11
On Fri, 14 Dec 2007 13:07:11 -0800, Jon Skeet [C# MVP] <sk***@pobox.co m>
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.ch sh.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.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 #13
Marc Gravell <ma**********@g mail.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.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 #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 "NotSupport ed"
or "InvalidOperati on" (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
3329
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
2606
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
9647
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
9489
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
10357
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
10162
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
10101
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7509
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
6744
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
5528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4063
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

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.