开发者

Why do we need to use out keyword while calling a method

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 dif开发者_C百科ferent 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


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.


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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜