tags:

views:

152

answers:

5

When a method is defined with an out parameter, why do I have to specify the out keyword when calling it. Its already there in the method definition, and the runtime should know that any parameter passed will be an out parameter.

It would make sense if the compiler will accept the argument with or without out keyword, with different semantic, but if you MUST add the keyword to make the code compile, whats the use? Shouldn't the compiler handle it automatically?

Same for ref

+8  A: 

It is really great for readability. Also it will help you to avoid unexpected behaviors. While calling method with out param you will definitely know that the value of passed variable can be changed.

Incognito
Not just 'can be changed' if you pass a parameter with 'out' it will be changed. Out parameters must be set before the method returns.
CnTwo
Yes value mast be set in method body block, but I mean that you can set the same value so no change will be noticed.
Incognito
+7  A: 

This requirement is not there for the compiler's sake. f (x, out y) instantly informs whoever is reading the code that y is going to be overwritten after f returns, without the need of looking up the definition of f, saving them mental CPU cycles.

Anton Tykhyy
A: 

This is a good point, perhaps it has to do with readability. lets say we have a method with two parameters, like so

bool TryGetString(string input, out string output)

without having to specify the out parameter, just a simple look at someone calling that method, it wouldn't make complete since.

Meiscooldude
A: 

when you call a method with out keyword, your calling code knows for sure that it is passed by reference. In some cases you might encounter a method in 3rd party library that is having out keyword in definition at that time when you call that method, you don't know if the argument is passed by reference or value. So you are forced to used out in the calling method for readabilty.

this. __curious_geek
+3  A: 

May be because C# allows you to write overloads like this:

class X
{
    public void Y(int i) { ... }
    public void Y(out int i) { ... }
}

In this case compiles can't understand that method with keywork out should be called if you don't write this keyword when you call the method. And generally you should write out when method declared with this keyworrd.

And of course when you write out when you call method, you definitly know that this variale can be changed in method. It's very readable.

MSDN Article

Pavel Belousov