1

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;
}
5
  • 3
    You want to use LINQ Cast<type>. msdn.microsoft.com/en-us/library/vstudio/… Commented May 14, 2014 at 11:19
  • 1.You can't pass class as a parameter, you can pass instances. 2.Don't use ArrayList use List<T> instead. 3. Your code won't compile for at least 2 reasons. Commented May 14, 2014 at 11:21
  • Have you looked into generic methods? msdn.microsoft.com/en-us/library/twcad0zb.aspx Commented May 14, 2014 at 11:29
  • You cannot convert one class to another that easy. You should make custom converters to do that for your custom classes. And I didn't get what you want as return type. Look into IConvertible interface. Commented May 14, 2014 at 11:32
  • To send classes into methods the template parameters(<T>) are used. Just to let you know. Commented May 14, 2014 at 11:33

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.