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)
{
}
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With