Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

parameters - What is the purpose of the "out" keyword at the caller (in C#)?

When a C# function has an output parameter, you make that clear as follows:

private void f(out OutputParameterClass outputParameter);

This states that the parameter does not have to be initialized when the function is called. However, when calling this function, you have to repeat the out keyword:

f(out outputParameter);

I am wondering what this is good for. Why is it necessary to repeat part of the function specification? Does anyone know?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It means you know what you're doing - that you're acknowledging it's an out parameter. Do you really want the utterly different behaviour to happen silently? The same is true for ref, by the way.

(You can also overload based on by-value vs out/ref, but I wouldn't recommend it.)

Basically, if you've got an (uncaptured) local variable and you use it as a non-out/ref argument, you know that the value of that variable won't be changed within the method. (If it's a reference type variable then the data within the object it refers to may be changed, but that's very different.)

This avoids the kind of situation you get in C++ where you unknowingly pass something by reference, but assume that the value hasn't changed...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...