Generics and consatraints.

M

Michael S

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<T> where T : struct
{
//implementation for ValueTypes
}

class MyList<T> where 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
 
D

Dustin Campbell

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<T> where T : struct
{
//implementation for ValueTypes
}
class MyList<T> where 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<T> as 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.
 
M

Michael S

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top