473,767 Members | 2,226 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this a reasonable way to use generics?

All:

I have an interesting problem in front of me. does this sound reasonable,
or ridiculous?

I have to build something that is sort of like a style sheet for Windows
controls.
Picture a collection of dissimilar value types: a couple of Color types,
some ints, some strings etc.

I _could_ just use a hashtable of object to contain all of these, but since
they are value types, they would be boxed.

But what if I did this: (warning the syntax probably isn't spot on)
public class Element<T>
{
public T Value;
public Element(T value)
{
this.Value = value;
}
}

And then stored the element objects in my collection:
So, here is how I would store a couple of properties:
{
HashTable styleElements = new HashTable();
styleElements.A dd("BackgroundC olor", new Element<Color>( Color.Blue);
styleElements.A dd("FontName", new Element<string> ("Arial");
// and so on

//now accessing the collection:
aControl.Backgr oundColor =
((Element<Color >)styleElemen ts["BackgroundColo r"]).Value;
}

Is this a horrible, horrible idea, or is it preferable to directly storing
the value types in the hashtable (thereby boxing them)?
Nov 17 '05 #1
5 1290
It seems to me that you just made the boxing explicit (and probably less
efficient than the implicit one).

/LM

"J.Marsch" <jm*****@newsgr oup.nospam> wrote in message
news:ey******** ******@tk2msftn gp13.phx.gbl...
All:

I have an interesting problem in front of me. does this sound reasonable,
or ridiculous?

I have to build something that is sort of like a style sheet for Windows
controls.
Picture a collection of dissimilar value types: a couple of Color types,
some ints, some strings etc.

I _could_ just use a hashtable of object to contain all of these, but
since they are value types, they would be boxed.

But what if I did this: (warning the syntax probably isn't spot on)
public class Element<T>
{
public T Value;
public Element(T value)
{
this.Value = value;
}
}

And then stored the element objects in my collection:
So, here is how I would store a couple of properties:
{
HashTable styleElements = new HashTable();
styleElements.A dd("BackgroundC olor", new Element<Color>( Color.Blue);
styleElements.A dd("FontName", new Element<string> ("Arial");
// and so on

//now accessing the collection:
aControl.Backgr oundColor =
((Element<Color >)styleElemen ts["BackgroundColo r"]).Value;
}

Is this a horrible, horrible idea, or is it preferable to directly storing
the value types in the hashtable (thereby boxing them)?

Nov 17 '05 #2
Hmm. Looking back, I don't know whether I am much more efficient than
boxing, as I am now manually allocating a new class (the element), so there
is still an additional heap allocation.

But I want to get back to your comments about explicitly vs. implicitely
boxing. It was my understanding that if you pass a value type as the
parameter to a generic type, then you get a "real" value type, so boxing
does not have to occur. I had thought that was supposed to be a prime
benefit of using a the generic collections with value types. Am I wrong
here?

Or, when you say that I am now explicitly boxing vs implicitly boxing, are
you refering to the instatiation of the Element class? I'm still not sure
whether this is the way to go. It seems that if I am only going to read
from the list of elements once, then I'm losing by going with generics. But
what if I am going to load the collection once, and read from it many times?
Then it seems as though I am trading multiple unbox operations for casts.

I'm still not sure which is better/worse. Comments?


"Luc E. Mistiaen" <lu**********@a dvalvas.be.no.s pam> wrote in message
news:uO******** ******@TK2MSFTN GP12.phx.gbl...
It seems to me that you just made the boxing explicit (and probably less
efficient than the implicit one).

/LM

"J.Marsch" <jm*****@newsgr oup.nospam> wrote in message
news:ey******** ******@tk2msftn gp13.phx.gbl...
All:

I have an interesting problem in front of me. does this sound
reasonable, or ridiculous?

I have to build something that is sort of like a style sheet for Windows
controls.
Picture a collection of dissimilar value types: a couple of Color types,
some ints, some strings etc.

I _could_ just use a hashtable of object to contain all of these, but
since they are value types, they would be boxed.

But what if I did this: (warning the syntax probably isn't spot on)
public class Element<T>
{
public T Value;
public Element(T value)
{
this.Value = value;
}
}

And then stored the element objects in my collection:
So, here is how I would store a couple of properties:
{
HashTable styleElements = new HashTable();
styleElements.A dd("BackgroundC olor", new Element<Color>( Color.Blue);
styleElements.A dd("FontName", new Element<string> ("Arial");
// and so on

//now accessing the collection:
aControl.Backgr oundColor =
((Element<Color >)styleElemen ts["BackgroundColo r"]).Value;
}

Is this a horrible, horrible idea, or is it preferable to directly
storing the value types in the hashtable (thereby boxing them)?


Nov 17 '05 #3
I was refereing to the fact that you stash your value into a class member
which is equivalent to boxing.

/LM

"J.Marsch" <jm*****@newsgr oup.nospam> wrote in message
news:um******** ******@TK2MSFTN GP12.phx.gbl...
Hmm. Looking back, I don't know whether I am much more efficient than
boxing, as I am now manually allocating a new class (the element), so
there is still an additional heap allocation.

But I want to get back to your comments about explicitly vs. implicitely
boxing. It was my understanding that if you pass a value type as the
parameter to a generic type, then you get a "real" value type, so boxing
does not have to occur. I had thought that was supposed to be a prime
benefit of using a the generic collections with value types. Am I wrong
here?

Or, when you say that I am now explicitly boxing vs implicitly boxing, are
you refering to the instatiation of the Element class? I'm still not sure
whether this is the way to go. It seems that if I am only going to read
from the list of elements once, then I'm losing by going with generics.
But what if I am going to load the collection once, and read from it many
times? Then it seems as though I am trading multiple unbox operations for
casts.

I'm still not sure which is better/worse. Comments?


"Luc E. Mistiaen" <lu**********@a dvalvas.be.no.s pam> wrote in message
news:uO******** ******@TK2MSFTN GP12.phx.gbl...
It seems to me that you just made the boxing explicit (and probably less
efficient than the implicit one).

/LM

"J.Marsch" <jm*****@newsgr oup.nospam> wrote in message
news:ey******** ******@tk2msftn gp13.phx.gbl...
All:

I have an interesting problem in front of me. does this sound
reasonable, or ridiculous?

I have to build something that is sort of like a style sheet for Windows
controls.
Picture a collection of dissimilar value types: a couple of Color
types, some ints, some strings etc.

I _could_ just use a hashtable of object to contain all of these, but
since they are value types, they would be boxed.

But what if I did this: (warning the syntax probably isn't spot on)
public class Element<T>
{
public T Value;
public Element(T value)
{
this.Value = value;
}
}

And then stored the element objects in my collection:
So, here is how I would store a couple of properties:
{
HashTable styleElements = new HashTable();
styleElements.A dd("BackgroundC olor", new Element<Color>( Color.Blue);
styleElements.A dd("FontName", new Element<string> ("Arial");
// and so on

//now accessing the collection:
aControl.Backgr oundColor =
((Element<Color >)styleElemen ts["BackgroundColo r"]).Value;
}

Is this a horrible, horrible idea, or is it preferable to directly
storing the value types in the hashtable (thereby boxing them)?



Nov 17 '05 #4
> Or, when you say that I am now explicitly boxing vs implicitly
boxing, are you refering to the instatiation of the Element class?

Yes. That's exactly what he's referring to. Creating an instance of
Element that holds your value type _is_ boxing. You're just doing what
the CLR would do anyway. This should illustrate two things to you:
first, that you should just shove the value types into the Hashtable
and let the CLR box them, and second, that for the most part those who
wring their hands shouting, "Boxing! Boxing! Oh the horror!" are for
the most part blowing smoke. Boxing is just simply what you've done in
the code you posted. It's not that big a deal... ceratinly not worth
building an entire new class and adding a bunch of machinery just to
avoid it.

Just let the CLR box the value type. You won't even notice. :)

To answer your other question, generics come into their own when you
want to create an aggregate structure (for example... there are other
situations besides aggregates) that will hold _one particular_ value
type. Then you can say: Hashtable<strin g, DateTime> and the DateTime
types stored in the hash table will _not_ be boxed. However, IMHO, this
is the least interesting part of generics: their run-time efficiency
benefits. The most interesting thing about generics is that they allow
for much better compile-time checking of your code, since the compiler
now understands what it is you want to do. As a result, you get
type-safe collections, which to me is far more significant than saving
a few cycles here and there (although the latter is nice, too).

In your case, generics won't help you: your collection does not hold a
uniform type of thing. This is one case in which the current
(non-generic) collections are what you need. As I said, just ignore the
whole boxing thing... it's not going to have a significant impact.

Nov 17 '05 #5
That clears things up, I believe. Thank you both for posting, I appreciate
it!
"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Or, when you say that I am now explicitly boxing vs implicitly

boxing, are you refering to the instatiation of the Element class?

Yes. That's exactly what he's referring to. Creating an instance of
Element that holds your value type _is_ boxing. You're just doing what
the CLR would do anyway. This should illustrate two things to you:
first, that you should just shove the value types into the Hashtable
and let the CLR box them, and second, that for the most part those who
wring their hands shouting, "Boxing! Boxing! Oh the horror!" are for
the most part blowing smoke. Boxing is just simply what you've done in
the code you posted. It's not that big a deal... ceratinly not worth
building an entire new class and adding a bunch of machinery just to
avoid it.

Just let the CLR box the value type. You won't even notice. :)

To answer your other question, generics come into their own when you
want to create an aggregate structure (for example... there are other
situations besides aggregates) that will hold _one particular_ value
type. Then you can say: Hashtable<strin g, DateTime> and the DateTime
types stored in the hash table will _not_ be boxed. However, IMHO, this
is the least interesting part of generics: their run-time efficiency
benefits. The most interesting thing about generics is that they allow
for much better compile-time checking of your code, since the compiler
now understands what it is you want to do. As a result, you get
type-safe collections, which to me is far more significant than saving
a few cycles here and there (although the latter is nice, too).

In your case, generics won't help you: your collection does not hold a
uniform type of thing. This is one case in which the current
(non-generic) collections are what you need. As I said, just ignore the
whole boxing thing... it's not going to have a significant impact.

Nov 17 '05 #6

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

Similar topics

27
2462
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
3104
by: Mr.Tickle | last post by:
So whats the deal here regarding Generics in the 2004 release and templates currently in C++?
23
2550
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
9404
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
10168
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
10009
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
9959
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,...
0
8835
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
7381
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
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
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
3
2806
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.