Wael Ahmed
Wael Ahmed

Reputation: 13

method that returns array

I'm starting out with C# and I created a method to add values to an array from a text stream and return the array as follows:

    private static string[] getLines(StreamReader myStream)
    {
        string[] lines;
        while (!myStream.EndOfStream)
        {
           lines = new string[] { myStream.ReadLine() };
        }

        return lines;
    }

I'm getting a use of unassigned variable 'lines' in the return parameter.

Upvotes: 1

Views: 137

Answers (3)

Akanksha Gaur
Akanksha Gaur

Reputation: 2686

The error you are getting is because of the unintialized parameter lines being used. If you want to read the whole file, instead of reading lines in iteration use ReadToEnd(). It will help in avoiding the while loop.

  private static string[] getLines(StreamReader myStream)
  {
      string[] lines = null;
      if(myStream != null)
      {
          lines = myStream.ReadToEnd().Split('\n');
      }
      return lines;
  }

You can also use .Split(new []{Environment.NewLine}, StringSplitOptions.None); to get the array which avoids the \n magic string that will not work cross platform.

Upvotes: 1

Moeri
Moeri

Reputation: 9294

You'll need to initialize the variable 'lines', because the compiler recognizes the possibility that your loop will contain zero elements, and you cannot return an uninitialized variable as the value for a method. But that is the least of your problems. You are not adding to the array, in fact, you cannot increase the capacity of an array once it has been initialised. You'll see that when this code runs, you will simply get an array of length 1 that only contains the last element of the text. This is because you are constantly reinitializing your array. (Notice the word 'new'?)

Your method would be better served with a list:

    List<string> lines = new List<string>();
    while (!myStream.EndOfStream)
    {
       lines.Add(myStream.ReadLine());
    }

    return lines.ToArray();

Upvotes: 5

WoLfulus
WoLfulus

Reputation: 1977

try this

private static string[] getLines(StreamReader myStream)
{
    List<string> lines = new List<string>();
    while (!myStream.EndOfStream)
    {
       lines.Add(myStream.ReadLine());
    }
    return lines.ToArray();
}

Upvotes: 0

Related Questions