0

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;

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by RicardoE
0

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

public LinkedList<LinkedList<LevelNode>> ExistingXMLList;
-1

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?

1

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.

Comments
Nice answer
0

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

This article has been dead for over six months. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.