Typecasting lists

  • Thread starter Thread starter Thomas Lorenz
  • Start date Start date
T

Thomas Lorenz

Hi,

I want to pass a List<string> to a method which requires a List<object>
parameter. I wonder if there is a comfortable way for typecasting the
stringlist without having to copy each item.
 
Thomas said:
I want to pass a List<string> to a method which requires a List<object>
parameter. I wonder if there is a comfortable way for typecasting the
stringlist without having to copy each item.

You need to use List<T>.ConvertAll<TOutput>() or some other copying /
conversion - there's no way to typecast, because covariance isn't
supported by C#'s generics.

-- Barry
 
Do you control the method in question? If so, you could make it:

void SomeMethod<T>(List<T> list) {}

This would allow you to pass *any* list to it in a type-safe manner.
For instance, inside SomeMethod you will only be able to treat items as
"T" instances, so you won't be able to add random items (but you can if
you can guarantee the item is a T, e.g. by adding the "where T : new()"
clause and creating the new item yourself). Also, unless you need the
full List<T> functionality, it may be adviseable to make your parameter
IList<T> or even IEnumerable<T>.

Note that the T does not have to be specified in usage; the compiler
will infer it:

List<string> strings = new List<string>();
strings.Add("abc");
strings.Add("def");
SomeMethod(strings);

Marc
 

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

Back
Top