views:

30

answers:

2

I've a method in a separate class from my main form that I've created that returns a List, and adds items to the List from the lines of a a file using something like this:

public List<string> testMethod(string data);
StreamReader read = new StreamReader(data);
List<string> lines= new List<string>();
while(read.Peek >= 0)
{
  lines.Add(read.ReadLine());
}
return lines;

That doesn't display any errors as detected by Intellisense, so I was feeling like I was a real life programmer for my thoughtfulness. Then I realized back in my main class, I don't actually know how to use the returned data. I've never made a method before that returned data. I google'd this issue, but I'm not sure I'm wording it properly as I havn't found anything concreate What I'd like to do is iterate over every item in returned List, but I don't know how to deal with the data from the form that called the method. Does this make sense, or am I going about this wrong?

+1  A: 

Use a foreach loop on the result of the method call:

List<string> items = testMethod(data);
foreach (string item in items)
{
    // ...
}

However your method doesn't seem that useful - it doesn't really do anything. It might be better just to open the file directly from your calling code and handle the lines as they are read. This will avoid creating a temporary list.

Mark Byers
+1 - you beat me to it
Sohnee
Well I'm actually parsing a stream of data from a web client, that was a simplified version of the method, but thanks for point out how to use the data. You'd think I would have accident'd my self onto that by now :)
Stev0
A: 

If you mean how to use the data returned from you method, its pretty easy:

List<string> response = testMethod("file");

foreach ( string line in response )
{
  Console.WriteLine(line);
}

One thing, make sure to close the stream in the method you created:

read.Close();
return lines;

Hope it helps, Best of luck!

David Conde