Declaring an array of linked list in C#

How do I declare an array of some class in C#? I wonder if it is even allowed or possible.

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 this the way:

string [2] inputdata;

Recommended Answers

All 4 Replies

Maybe you should use a LinkedList of LinkedList, would be slower but more powerfull as LinkedList are dinamically Allocated.

public LinkedList<LinkedList<LevelNode>> ExistingXMLList;

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] which would normally be passed in the constructor?

If I was not using an array, it would be done like this:

XmlTextReader r;

r = new XmlTextReader (filename);

Should I use a linked list of XmlTextReader classes? Would that work?

You could declare an array of LinkedList objects like this

LinkedList<int>[] array = new LinkedList<int>[5];

Next question: Then how would you pass the filename to r[0] and r[1] which would normally be passed in the constructor?

These statements here

XmlTextReader[] r;
r = new XmlTextReader [2];

Only created the array. You still have to instantiate the objects inside the array, so the constructors are still valid.

r[0] = new XmlTextReader(filename);
r[1] = new XmlTextReader(filename2);

With that said, don't use XmlTextReader. It's deprecated since 2.0 in favor of using XmlReader and the XmlReader.Create() method.

commented: Nice answer +4

With that said, don't use XmlTextReader. It's deprecated since 2.0 in favor of using XmlReader and the XmlReader.Create() method.

True! :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.