By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,772 Members | 1,425 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,772 IT Pros & Developers. It's quick & easy.

Generics and consatraints.

P: n/a
When reading about generics, one benefit is to have different
implementations depending on reference/value type. As far as I know, List<T>
does not box/unbox ValueTypes.

How do they do that? A lot of if/else statements in the list?

Or can you do something like

class MyList<Twhere T : struct
{
//implementation for ValueTypes
}

class MyList<Twhere T : class
{
//implementation for Object
}

Obviously the above does not compile. While lost in msdn searching
aimlessly; usenet is my last hope of enlightment.

Thanks
- Michael S
Feb 2 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
When reading about generics, one benefit is to have different
implementations depending on reference/value type. As far as I know,
List<Tdoes not box/unbox ValueTypes.

How do they do that? A lot of if/else statements in the list?

Or can you do something like

class MyList<Twhere T : struct
{
//implementation for ValueTypes
}
class MyList<Twhere T : class
{
//implementation for Object
}
Obviously the above does not compile. While lost in msdn searching
aimlessly; usenet is my last hope of enlightment.
No, the removal of boxing operations is a by-product of using generics. Constraints
aren't involved. For example:

class MyList<T>
{
T[] _internalArray;

public AddItem(T item)
{
// blah...
}
}

Boxing occurs with ArrayList because the values stored in the ArrayList must
be cast to System.Object (a reference type). With generics, that cast is
unnecessary.

If I instantiate MyList<Tas a MyList<int>, a type is created at runtime
which looks like this:

class MyList<int>
{
int[] _internalArray;

public AddItem(int item)
{
// blah...
}
}

No boxing is necessary.

Best Regards,
Dustin Campbell
Developer Express Inc.
Feb 2 '07 #2

P: n/a
"Dustin Campbell" <du*****@no-spam-pleasedevexpress.comwrote in message
news:c1**************************@news.microsoft.c om...

No boxing is necessary.

Best Regards,
Dustin Campbell
Thanks Dustin and of course.
I'm sorry for you having to deal with my Friday Afternoon Syndrome. =)

Guess I got stuck in the class/struct constraints and didn't bother to
think.

- Michael S
Feb 2 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.