As everyone says, you can simply use ref
.
I'm going to suggest an alternative approach, just so you are aware of it.
You could write a method that returned an IEnumerable<Line>
where Line
is a very simple class that just encapsulates a line of text and a line number:
public class Line
{
public string Text;
public int Number;
}
Then your method to read the lines could look something like this:
public IEnumerable<Line> ReadLines(StreamReader sr)
{
int number = 0;
while (true)
{
string line = sr.ReadLine();
if (line == null)
break;
++number;
if (wantLine(line)) // Some predicate which decides if you want to keep the line.
yield return new Line{Text = line, Number = number};
}
}
Then you could use it as follows:
public void Test()
{
StreamReader sr = new StreamReader("Whatever");
foreach (var line in ReadLines(sr))
{
if (line.Text == "SomeSpecialValue")
doSomethingWith(line.Text, line.Number);
}
}
This is more work to write, but I think it can result in clearer code, and it also has the advantage that the line number counter is entirely hidden inside ReadLines()
. (It's not a member of your class in the sense that it is a field in your class; it's just a local variable in the method.)