Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# support inout parameters?

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.

like image 501
Lee White Avatar asked May 02 '13 07:05

Lee White


People also ask

What does %d do in C?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.

What is && operator in C?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int . Both operands must have an arithmetic or pointer type.


2 Answers

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

like image 112
pyrocumulus Avatar answered Oct 15 '22 21:10

pyrocumulus


Use ref keyword instead of out. This will force the caller to initialize the argument before calling.

From the MSDN - ref (C#)

An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.

like image 22
Henrik Avatar answered Oct 15 '22 23:10

Henrik