Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
{
}
like image 998
shape87 Avatar asked Aug 14 '12 14:08

shape87


2 Answers

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);
}
like image 43
Jaime Torres Avatar answered Sep 25 '22 02:09

Jaime Torres


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.

like image 74
vcsjones Avatar answered Sep 26 '22 02:09

vcsjones