Does C# support inout parameters?

Lee White picture Lee White · May 2, 2013 · Viewed 15.9k times · Source

In C#, I am using a StreamReader to read a file, line per line. I am also keeping the current line's number in an int, for reports of possible error messages.

Reading each line goes along with some tests (for instance, lines beginning with # are comments, and need to be skipped), so I am planning to place the whole reading procedure in a function, which will keep reading until it encounters a useful line, and then returns that line. If it encounters EOF it will simply return null.

I thought I was being clever when I defined this function as string read(StreamReader sr, out int lineNumber), but now it turns out that C# won't be able to do something like lineNumber++ inside that function. It assumes that the variable has not been assigned yet, probably because it has no way to know whether it has been assigned in advance of this function call.

So, the problem is simple: how can I specify that this variable is an inout parameter (I think that's the term; I've heard it being mentioned in the context of other programming languages)? Is this even possible in the first place? I am absolutely not going to make lineNumber a member of my class, so that is not an option.

Answer

pyrocumulus picture pyrocumulus · May 2, 2013

In that case you need a ref parameter instead of out. With the out keyword the responsibility for assigning/instantiating a value lies within the calling called method; with ref it lies outside of the method being called.

Also see: When to use ref vs out