is there anyway to unbox an object to its real type?
Basically I am given an ArrayList, the array list are actually a list of int or double, or maybe other types ( it can be either, but it is either all int or double, no mix). Now, I will have to return a List<double> or List<int> or other list, depending on what is the real type.
public List<T> ConvertToList<T>(ArrayList arr)
{
var list1 = new List<T>();
foreach(var obj in arr)
{
// how to do the conversion?
var objT = ??
list1.Add(objT);
}
return list1;
}
Any idea?
If you're using .NET 3.5, there's a much easier way to do this:
public List<T> ConvertToList<T>(IEnumerable original)
{
return original.Cast<T>().ToList();
}
(I've generalised the parameter to just IEnumerable as we're not using anything specific to ArrayList here.)
You can use the Convert class.
var objT = (T)Convert.ChangeType(obj, typeof(T));
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