ArrayList.ToArray(Type) Or ArrayList.CopyTo(Array)

转自:http://blogs.geekdojo.net/richardhsu/archive/2003/11/08/268.aspx

I was using ArrayList.CopyTo(Array) to convert arraylist to a type[] array.

I thought ArrayList.ToArray(Type) was for intrinsic types (int, string etc.) but forgot that one the facilitites of OOP is that types that we define can be treated as instinsic types for most occasions. Today I came across a code that showed the use of ArrayList.ToArray(Type) for a type defined by the programmer.

...
return (Contact[])mContacts.ToArray(typeof(Contact));
...

here mConstacts is of type ArrayList, and Contact is a class.

I was doing the following till now :-

C# :-

Contact[] contacts = new Contact[mContacts.Count];

mContacts.CopyTo(contacts);

return contacts;

I have yet to peek into the IL to see the difference/similarity between the two approaches in terms of internals, but the first one at least requires less code and fits in a single line. :-)

 

你可能感兴趣的:(ArrayList)