4

I got the compile error message "Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)" when I tried to declare an array of linked lists.

public LinkedList<LevelNode>[2] ExistingXMLList;

Also, if I wanted to create a small array of strings, isn't the following the correct way?

string [2] inputdata;

3 Answers 3

8

You declare an array with just [].

LinkedList[] XMLList;

Then you instantiate it with the size.

XMLList = new LinkedList[2];

Or both at the same time:

LinkedList[] XMLList = new LinkedList[2];

To add LinkedLists to this array you type:

XMLList[0] = new LinkedList();
XMLList[1] = new LinkedList();
Sign up to request clarification or add additional context in comments.

5 Comments

Oops, sorry about that. I never use arrays.
No need to apologize, Visual Studio spoils us all!
What if you are using an array of a class where the constructor seems to require a paramenter? If you use new like this: XmlTextReader[] r; r = new XmlTextReader [2]; Then how would you pass the filename to r[0] and r[1] ?
This code is instantiating an Array. If you want to add values to that array you have to do XMLList[0] = new XMLList();
I am not able to use in a .NET Core 3.1 console app. Did this change?
1

try this:

LinkedList[] ExistingXMLList = new LinkedList[2];

1 Comment

I thought I was crazy, but then I decided that even with 15.5k rep he could still make a mistake.
-1

You can try this
LinkedList<>[] adjacentList = new LinkedList<>[2];
using the generic type linked list requires 1 type parameter

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.