Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 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 Answer

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...