List <string> for object []
I have a method that returns a List<string>
, and I'm trying to pass this to the AddRange(Object[])
method for a ComboBox
.
How can I convert my List<string>
to Object[]
?
I suppose I could do foreach
, but I would rather use AddRange(Object[])
as it is faster (and produces less code).
EDIT
The following works great:
var list = new List<string>(); object[] array = list.ToArray<object>(); comboBox.AddRange(array);
However, for another note, any reason that I would like to perform above rather than:
var list = new list<string>(); comboBox.AddRange(list.ToArray<object>());
Link arrays are covariant ( slowly covariant ) with arrays of their base classes (and with arrays of their interfaces and other arrays), so you can:
AddRange(mystrings.ToArray());
mystrings.ToArray()
is a string[]
covariant with object[]
(so AddRange
will accept it)
From 12.5 Covariance of Arrays
For any two reference types A and B, if there is an implicit reference conversion (section 6.1.4) or an explicit reference conversion (section 6.2.3) between A and B, then the same reference conversion of type A [R] to array type B [R]