Other Software > Developer's Corner
[Solved] C# Arraylist
mediaguycouk:
I'm getting stuck on the superhard c# assignment 6, but on the easy stuff.
I have this code...
--- Code: C# ---// Create an instance of StreamReader to read from a file.// The using statement also closes the StreamReader.using (StreamReader sr = new StreamReader(fileToEncryptText.Text)){ // Temp string for lines string line; // Create an array list for the file contents ArrayList fileContentsArrayList; int i = 0; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { // Place line into array fileContentsArrayList.Add(line); // Increase [i] i++; //encryptOutputText.Text += encrypt.EncryptSingleLine(line) + "\r\n"; } // Convert ArrayList into an Array string[] fileContentsArray = (string[])fileContentsArrayList.ToArray();}
but it isn't compiling due to 'Use of unassigned local variable fileContentsArrayList'. I know this is because there is a possibility that using() doesn't run and nothing gets put into it.
My problem is that I can't really add anything into the array to initialise it that isn't part of the streamreader. So how can I make sure that it initialises without breaking what the program does?
Many thanks :-*
CWuestefeld:
Are you sure that the problem is 'Use of unassigned local variable'? That message isn't an error, just a warning, so it wouldn't prevent compilation. However, I do see a different error.
What I do see is that you've only declared fileContentsArrayList at line 9. That is, you've created a variable by that name, that can hold a reference to an object of type ArrayList. But, despite your comment on line #8, you have not actually created an instance of such an object for your variable to point at.
What you want at line #9 is
Spoiler
--- Code: C# ---ArrayList fileContentsArrayList = new ArrayList();
mediaguycouk:
That's the error message that is stopping compiling, but you have fixed the error. It now compiles and I thank you :)
CWuestefeld:
You understand the difference between a variable representing a reference to the object, and thus requiring a separate step to actually create the object that it references? This is pretty key to understanding what's going on with C#.
mediaguycouk:
I admit that I do have a lot of trouble with that.
My GF comes from a Java background and finds all this very easy but I come from an actionscript / PHP background that just doesn't have these things.
But then that's why I love this forum. It has helpful people that don't mind sharing knowledge.
Navigation
[0] Message Index
[#] Next page
Go to full version