473,785 Members | 2,291 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics in .NET 2.0 SUCK

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 quite large vector and
matrix libraries that I would love to convert to use generics.

Imagine my surprise when I found out that what I want is basically
impossible. I want a complex number class that can work with any basic data
type like so: complex<float>, complex<double> , complex<decimal > and so on.
This is something that is done very often in C++ and one of the main
applications of generics there.

This was my first try (this is only an excerpt):

struct complex<T>
{
public T re,im;
complex<T>(T re,T im)
{
this.re=re;this .im=im;
}
complex<T> Sum(complex<T> a,complex<T> b)
{
return new complex<T>(a.re +b.re,a.im+b.im );
}
}

Something like this would work in C++, since it does not have constraints on
type parameters. But in .NET, when you specify a type parameter without
constraints it is assumed to be a System.Object, which of course does not
have a + operator.

So I thought, probably there is a way to specify a method constraint for T
such that T must have a certain (static) method or a certain operator
method. But the only thing like this is the new() constraint to specify
that a class must have a default constructor.

My second thought was that there might be some interface like IArithmetic.
This is of course complicated by the fact that interfaces can not contain
static methods. But something like

interface IArithmetic<T> {
void Add(T a);
void Subtract(T a);
void Multiply(T a);
void Divide(T a);
}

should do the trick. This would not be very elegant, but quite sufficient.
Given that there is an interface called IComparable<T> this should not be
too much to ask. Maybe there should even be something more granular like

interface IAddable<T> {
void Add(T a);
}

....

interface
IArithmetic<T>: IAddable<T>,ISu btractable<T>,I Multipliable<T> ,IDivisible<T>
{
}

or something. This solution would be similar to the approach taken with
IComparable and IComparable<T>.

But no such interface exists in the System namespace. So I would have to
wrap all the basic data types into structs that actually implement this
interface, like so:

struct ArithmeticInt : IArithmetic<int > {
private int value;
...
}

struct ArithmeticDoubl e : IArithmetic<dou ble> {
private double value;
...
}

But this would be a lot of work and, even worse, would lead to absymal
performance since in my experience the .NET JIT compiler is too dumb to get
rid of the wrapper code.

There are of course some workarounds like having a separate type parameter
for the operations, like this:

struct Complex<T,Ops> where Ops:IArithmetic Ops<T>
{
...
}

But this yields inacceptable performance.

What is really required is a way to specify *method* *constraints* instead
of just interface constraints and the new() constraint.

Another option would be to allow static methods in interfaces and to provide
an IArithmethic interface in the System namespace, but I would prefer the
first option.

Without something like this, generics are only good for typed collections.
Adding so much new syntax and complexity just to make collections faster
and more type safe seems like a waste of time!
Nov 16 '05 #1
10 2606
Just to back up my assertion that the .NET JIT is not capable of removing
wrapper code, here is a small benchmark. YMMV, but on my machine the second
loop always takes about twice as long as the first loop. So using wrapper
classes is not an option for performance-critical code.

----------------------------------------------------------------------
#region Using directives

using System;
using System.Collecti ons.Generic;
using System.Text;

#endregion

namespace ConsoleApplicat ion1
{
interface IAddable<T>
{
void Add(T a);
}
struct AddableInt : IAddable<int>
{
int value;
public void Add(int a)
{
value += a;
}
}
class Program
{
static void Main(string[] args)
{
//This is for the JIT
Test();
//This one is for real
Test();
Console.ReadLin e();
}
static void Test() {
int x0 = 0;
AddableInt x1 = new AddableInt();
DateTime time0 = DateTime.Now;
for (int i = 0; i < 1000000000; i++)
{
x0 += i;
}
TimeSpan delta0 = DateTime.Now - time0;
DateTime time1 = DateTime.Now;
for (int i = 0; i < 1000000000; i++)
{
x1.Add(i);
}
TimeSpan delta1 = DateTime.Now - time1;
Console.WriteLi ne(delta0);
Console.WriteLi ne(delta1);
}
}
}

Nov 16 '05 #2
"Ruediger Klaehn" <kl****@gamemak ers.de> wrote:

[...rant deleted...]
Without something like this, generics are only good for typed collections.
Adding so much new syntax and complexity just to make collections faster
and more type safe seems like a waste of time!


Ah well, I think making collections typesafe and faster is worth all the new
syntax and complicity.
Oh, and my girlfriend would probably agree with me, too, she'd love to have
more typesafety! :)

Sam
--
But no constraints is tough, yes! And I got the naggin feeling I read
somewhere it should know constraints. Memory is a strange beast.
Nov 16 '05 #3
On Tue, 27 Jul 2004 14:47:18 +0200, Ruediger Klaehn
<kl****@gamemak ers.de> wrote:

<snip>

Imagine my surprise when I found out that what I want is basically
impossible. I want a complex number class that can work with any basic data
type like so: complex<float>, complex<double> , complex<decimal > and so on.
This is something that is done very often in C++ and one of the main
applications of generics there. <snip>

Yes, it is unfortunately impossible. I don't think there is a chance
of this changing for 2.0, but you should take this discussion to the
beta newsgroups and try to influence the future direction, because I
know this very subject is being given some thought:
http://communities.microsoft.com/new...idbey&slcid=us

Without something like this, generics are only good for typed collections.
Adding so much new syntax and complexity just to make collections faster
and more type safe seems like a waste of time!


It's subjective, but I would have to disagree. Collections are
pervasive in many of the applications I work with, and generics will
make them not only type safe and performant, but also make the code
more elegant.

--
Scott
http://www.OdeToCode.com
Nov 16 '05 #4
Scott Allen <bitmask@[nospam].fred.net> wrote:
Without something like this, generics are only good for typed collections.
Adding so much new syntax and complexity just to make collections faster
and more type safe seems like a waste of time!


It's subjective, but I would have to disagree. Collections are
pervasive in many of the applications I work with, and generics will
make them not only type safe and performant, but also make the code
more elegant.


In particular, the ability to have efficient lists of value types
without boxing will be very nice - a list of bytes will no doubt be
useful in many places where currently we use MemoryStream, etc.

I'm with you - type-safe and efficient collections are very
important...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Scott Allen wrote:

[snip]

Without something like this, generics are only good for typed collections.
Adding so much new syntax and complexity just to make collections faster
and more type safe seems like a waste of time!


It's subjective, but I would have to disagree. Collections are
pervasive in many of the applications I work with, and generics will
make them not only type safe and performant, but also make the code
more elegant.

I guess I overreacted a bit. Of course C# generics are still much faster
than java "generics" and not as complex as C++ templates, and they will be
very useful in many situations.

But the fact that it is not even possible to write a fast generic complex
class is a big disappointment. Especially since it would be extremely
simple to add something IArithmetic<T> to all base data types. After all
they added the generic interface Comparable<T>.

I still don't get why such a simple thing has been overlooked!
Nov 16 '05 #6
"Beeeeeeeeeeeev es" <Be************ **@discussions. microsoft.com> wrote in
news:76******** *************** ***********@mic rosoft.com...
The reason Generics in .NET 2.0 SUCK ?
Likely because they are a complete crib off templates in C++, which ALSO SUCK!!!
Ever implemented a type-safe list in C#?
You do know what type-safety is, don't you?
And... you do know what a list is?
They are the most POOR idea for a way of programming I have ever seen.


Apparently you're new to programming...

Niki
Nov 16 '05 #7
Ruediger Klaehn wrote:
Imagine my surprise when I found out that what I want is basically
impossible. I want a complex number class that can work with any
basic data type like so: complex<float>, complex<double> ,
complex<decimal > and so on. This is something that is done very often
in C++ and one of the main applications of generics there.


Welcome to the club :-(

<http://groups.google.com/groups?dq=&...dm=OVjxavQbEHA.
1048%40tk2msftn gp13.phx.gbl&pr ev=/groups%3Fdq%3D% 26num%3D25%26hl %3Den%26lr%3
D%26ie%3DUTF-8%26group%3Dmic rosoft.public.d otnet.languages .csharp%26start %3D
525>

Regards,

Andreas

Nov 16 '05 #8
So, let me get this straight... boxing and unboxing are acceptable practices
in your code? Remind me never to run one of your apps. ;-)

As for a "complete crib off templates in C++"... erm, what do you think most
of the C# language is derived from? C++ style languages (Java, C++, C,
etc..).

--
Kyril

"Beeeeeeeeeeeev es" <Be************ **@discussions. microsoft.com> wrote in
message news:76******** *************** ***********@mic rosoft.com...
| The reason Generics in .NET 2.0 SUCK ?
| Likely because they are a complete crib off templates in C++, which ALSO
SUCK!!!
| They are the most POOR idea for a way of programming I have ever seen.
|
<snip>
Nov 16 '05 #9

"Niki Estner" <ni*********@cu be.net> wrote in message
news:ue******** ******@TK2MSFTN GP09.phx.gbl...
"Beeeeeeeeeeeev es" <Be************ **@discussions. microsoft.com> wrote in
news:76******** *************** ***********@mic rosoft.com...
The reason Generics in .NET 2.0 SUCK ?
Likely because they are a complete crib off templates in C++, which ALSO

SUCK!!!
Ever implemented a type-safe list in C#?
You do know what type-safety is, don't you?
And... you do know what a list is?
They are the most POOR idea for a way of programming I have ever seen.


Apparently you're new to programming...


No, he's just here to complain. I consider him a troll at this point.
Nov 16 '05 #10

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

Similar topics

27
2463
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!
2
3106
by: Mr.Tickle | last post by:
So whats the deal here regarding Generics in the 2004 release and templates currently in C++?
23
2555
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.
5
2921
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have an "AppleBasket" which is a class that contains a collection of apples. So, some code: class Fruit{ }
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...
7
3257
by: SpotNet | last post by:
Hello NewsGroup, Reading up on Generics in the .NET Framework 2.0 using C# 2005 (SP1), I have a question on the application of Generics. Knowingly, Generic classes are contained in the System.Collections.Generic namespace. Literature I have read on this ties generics in with collections, hence articulate their examples as such. That's fine, I understand what is being said. My question is more towards the application and implementation...
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...
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
10163
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
8988
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
7510
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
5397
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...
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
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.