9

I've created a class called listItem and the following list:

List<listItem> myList = new List<listItem>();

At some point in my code, I want to convert it to an array, thereby using:

listItem[] myArray = myList.ToArray();

Unfortunately, this doesn't work, and I get this error message:

Cannot convert [...] listItem[] to [...] List<listItem>

I tried to figure this out, but very unsuccessfully...

Thanks in advance.

EDIT: My bad, the first code line I wrote was indeed mistyped!

Actually, all the code above works pretty well. My error was due to the fact that my function:

List<listItem> myFunction()

returned myArray, hence the conversion problem... It is now fixed. :)

Thank you all for your answers.

4
  • 1
    A listitem isn't the same as a list<> ;) Commented Apr 3, 2012 at 9:20
  • 2
    Your first line won't compile to start with, and the error message suggests a conversion the other way round. Please show a short but complete program demonstrating the problem, and the verbatim error message. Commented Apr 3, 2012 at 9:20
  • Is that typed in correctly? Your issue seems to have nothing to do with the ToArray() call. Commented Apr 3, 2012 at 9:20
  • 2
    The error message you've posted relates to converting array of ListItems into List<ListItem>, not the other way around. List<ListItem>.ToArray() should work perfectly fine. Post whole code or whole error message. Commented Apr 3, 2012 at 9:21

3 Answers 3

15

This is the error (as pointed out from Darkshadw and Jon Skeet)

listItem myList = new List<listItem>();

You are assigning the value of a List to a listItem.

Replace it with

List<listItem> myList = new List<listItem>();

to create a list of listItem. Then

listItem[] myArray = myList.ToArray();

will work.

Sign up to request clarification or add additional context in comments.

3 Comments

How to give size?
To get size: myArray.size. To set: myArray = new Array[5]; but deletes old array
It works. ToArray() on a List converts the list to array depending on the type. Thanks.
2

have you tried

listItem[] myArray = myList.ToArray(new listItem[]{});

in Java it works, im not sure in c#

Comments

0
string[] s = myList.ToArray();

Considering myList is list of string

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.