Reputation: 605
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?
Upvotes: 0
Views: 87
Reputation: 4637
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!
Upvotes: 0
Reputation: 838696
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.
Upvotes: 1