Reputation: 11
I have specific classes that I want to pass into an a method and I want to use that class in the method and return a version of that class.
protected Type [] Convert(ArrayList list, MyPersonalClass)
{
MyPersonalClass[] resArray = (MyPersonalClass[])list.ToArray(typeof(MyPersonalClass));
return resArray;
}
Upvotes: 1
Views: 88
Reputation: 38077
You want to use Generics for this, so to directly convert your example:
public T[] Convert<T>(ArrayList list)
{
return (T[])list.ToArray(typeof(T));
}
Then you can use it:
Convert<MyPersonalClass>(l);
The problem with doing it this way is that there is no way to guarantee the objects in the ArrayList are castable to MyPersonalClass
.
Instead you might be better off using a generic list of MyPersonalClass
and then you can just call ToArray()
on that if you need an array:
List<MyPersonalClass> list = new List<MyPersonalClass>();
list.Add(new MyPersonalClass());
var arr = list.ToArray();
Upvotes: 2