Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbox an Object to Its Type

Tags:

c#

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?

like image 981
Graviton Avatar asked Dec 29 '25 19:12

Graviton


2 Answers

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.)

like image 70
Jon Skeet Avatar answered Jan 01 '26 07:01

Jon Skeet


You can use the Convert class.

var objT = (T)Convert.ChangeType(obj, typeof(T));
like image 40
gsharp Avatar answered Jan 01 '26 09:01

gsharp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!