Link to home
Start Free TrialLog in
Avatar of campinam
campinam

asked on

Cast return of arrlist.ToArray(typeof(string)) ??

This is about the ToArray method of the ArrayList class in C#. Please look at this line of code:
string[] strarr = (string[])arrlist.ToArray(typeof(string));

Open in new window

ToArray is overloaded, one overload takes no arguments and returns an Object array, while the other (like above) returns an array of the specified type. But if it returns a string array (in this case), why do we have to cast again the string array it returns, to string[]?

1. One reason I've seen is that C# disallows implicit casting. But here a string array is assigned to a string array, so there should be no casting.

2. Another reason I've seen is that ToArray(Type) returns an array of objects. However, in the C# docs it "returns an array of the specified type".

So why is that cast needed?
ASKER CERTIFIED SOLUTION
Avatar of Wim_Bl
Wim_Bl
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of campinam
campinam

ASKER

So ToArray(Type) returns an array of objects? Then why in the C# docs it "returns an array of the specified type"? Only the first overload returns an object array.
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
string[] denotes an Array type where the constructor of the Array class sets elements of the array to strings. So string[] is still an Array class. A function can return a strign array, and the returned value can be assigned to a string[] variable without conversion, because they are the same type.
I guess "returns an array of the specified type" means it returns and Array object with elements of the specified type. But becaude the return type is Array, elements have type Object (string[] is a class derived from Array). Thank you for your helpful remarks.