C# Converting List<object> to Original Type without an Explicit Cast
Asked Answered
F

3

5

I'm having trouble converting a list object back to its original type without an explicit cast. My intention is to generalize methods so I could pass in different db Types such as Person or Company. I have no problem getting the values via reflection but I need to convert the actual list back to its original type List<typeT> instead of List<object> in the method I am passing it to. I am aware of the following methods:

 SomeList.ConvertAll(x => (typeT)x);
 SomeList.Cast<typeT>().ToList();

However for these methods I will have to explicitly cast typeT. I have tried the following:

formatted1.ConvertAll(x => Convert.ChangeType(x, typeT));

and

List<dynamic> newList = new List<dynamic>();
foreach (var p in SomeList)
{
   newList.Add(Convert.ChangeType(p, typeT);
}

No success thus far. Maybe I should have another game-plan for generalizing these methods altogether. right now I'm passing the lists in as follows:

public string returnJson(List<object> entity, string someString)
{
}
Flyblown answered 14/8, 2012 at 14:46 Comment(0)
A
6

It seems like making returnJson generic would resolve most of these problems:

public string returnJson<T>(List<T> entity, string someString)
{
}

Now returnJson can be used generically, like:

returnJson<Company>(listOfCompanies, "someString");

and

returnJson<Person>(listOfPersons, "someOtherString");

You can still reflect over the objects, but the list is always a list of the type that you need at compile time. No casting required.

Aberration answered 14/8, 2012 at 14:50 Comment(2)
I have to agree with this one. You beat me to the punch. :)Denigrate
Thanks alot, the generic methods have helped a great deal.Flyblown
C
1

Why not use generics, that way the calling function can do what it needs:

public string returnJson<T>(List<T> entity, string someString)
{
     //not sure what someString is for or why you need the type for this naming scheme

     JavaScriptSerializer jss = new JavaScriptSerializer();
     return jss.Serialize(entity);
}
Crinum answered 14/8, 2012 at 14:50 Comment(0)
T
0

You can use the dynamic keyword and reflection to create the list.

dynamic newList = Activator.CreateInstance(typeof(List<>).MakeGenericType(typeT));
foreach (var p in SomeList)
{
   newList.Add(p);
}
CallOtherMethodOverloadedForListOfPersonCompanyEtc(newList)
Trev answered 14/8, 2012 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.