Convert a custom type ArrayList to an Array in C#

If you ever tried to convert a custom type ArrayList to an Array you will most likely get an error:

This won’t work:

Job[] jobsArray = allJobs.ToArray();

Cannot implicitly convert type ‘object[]‘ to ‘JNetwork.Job[]‘. An explicit conversion exists (are you missing a cast?)

Neiter this:

Job[] jobsArray = allJobs.ToArray<Job>();

‘System.Collections.ArrayList’ does not contain a definition for ‘ToArray’ and the best extension method overload ‘System.Linq.Enumerable.ToArray<TSource>(System.Collections.Generic.IEnumerable<TSource>)’ has some invalid arguments

To solve the problem you will have to specify the custom type using the operator: “typeof”

And using the Cast type: “as”  will make a strong typing cast on top of the array.

So the way to do it would be as follow:

Job[] jobsArray = allJobs.ToArray (typeof(Job)) as Job[];