Graviton
Graviton

Reputation: 83264

Unbox an Object to Its Type

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?

Upvotes: 2

Views: 1751

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502016

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

Upvotes: 8

Filip Ekberg
Filip Ekberg

Reputation: 36297

You can just regular Type Cast like this

public List<T> ConvertToList<T>(ArrayList arr)
{
    var list1 = new List<T>();
    foreach(var obj in arr)
   { 
     // Like this 
     list1.Add((T)obj);

    }
    return list1;
}

Upvotes: 3

gsharp
gsharp

Reputation: 27937

You can use the Convert class.

var objT = (T)Convert.ChangeType(obj, typeof(T));

Upvotes: 3

Related Questions