user3636342
user3636342

Reputation: 11

Passing a Class as a parameter

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

Answers (1)

John Koerner
John Koerner

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

Related Questions