Additional output options

In C # 4, is there a good way to have an optional output parameter?

+47
Nov 27 '10 at 20:05
source share
5 answers

Not really, although you can always overload a method with another that does not accept an output parameter.

+46
Nov 27 '10 at 20:08
source share

Decorating parameters with the OptionalAttribute parameter also does not work. To expand on the previous sample, you will get something like:

private void Func( [Optional] out int optional1, [Optional] out string optional2) { /* ... */ } 

Please note that the above will compile (maybe unfortunately). However, trying to compile:

 Func(out i); 

will fail if an overload with a one-parameter signature is not explicitly specified.

To (theoretically) makes the above work a serious problem. When a method is called with an optional parameter omitted, a stack frame is created containing the values ​​of all parameters, and the missing values ​​are simply filled with the specified default values.

However, the out parameter is a reference, not a value. If this parameter is optional and not specified, which variable does it reference? The compiler still needs to fulfill the requirement that the "out" parameter be filled before any normal return from the method, since the compiler does not know a priori what additional parameters are specified by the caller (if any). This means that it would be necessary to refer to the dummy variable somewhere, so the method must fill something. Managing this dummy variable space would create an unpleasant headache for the compiler writer. I'm not saying that it would be impossible to make out the details of how this will work, but the architectural implications are great enough for Microsoft to convey this function in an understandable way.

+7
Mar 13 '12 at 19:29
source share

No.

To make it "optional", in the sense that you do not need to assign a value in a method, you can use ref .

+5
Nov 27 '10 at 20:07
source share
 private object[] Func(); 

assign as much as you want in the array of returned objects, and then use them! but if you mean the optional output, something like

 private void Func(out int optional1, out string optional2) 

and then you call something like

 Func(out i); 

then the answer is not you. also the C # and .NET framework have a lot of data structures that are very flexible, such as List and Array , and you can use them as an output parameter or as a return type, so there is no need to implement a way to get optional output parameters.

+2
Nov 27 '10 at 20:08
source share
 public class Dummy<T> { public T Value; } 

Then use functionDoSomething(out new Dummy<int>().Value , where int can be any type.

0
Apr 02 '13 at 12:16
source share



All Articles