Search code examples
.netvb.netattributesoutput-parameter

The <Out()> Attribute. What useful purpose does is serve?


Under System.Runtime.InteropServices the <Out()> Attribute exists. But what is it for? I would be glad if you could use the following example as base for your answers.

 Shared Sub Add(ByVal x As Integer, ByVal y As Integer, <Out()> ByRef Result As Integer)
  Result = x + y
 End Sub

Solution

  • The purpose of that attribute is twofold:

    • Call-site handling, whether to enforce variable initialization or not
    • Marshalling

    If you were to call that method from C#, or a similar language with similar semantics, such a parameter would be known to the compiler to not need an initial value.

    In other words, you can do this:

    int a;
    CallSomeMethodWithOutParameter(out a);
    

    and the compiler knows that there is no need to ensure that a already has a value before making the call.

    On the other hand, without the attribute, the following would be needed, again in C#:

    int a = 0;                               // <-- notice initialization here
    CallSomeMethodWithOutParameter(ref a);   // <-- and ref here
    

    The other purpose is for method calls that will be marshalled into a different calling context, for instance through P/Invoke, to a different app-domain, or to a web service, to notify marshalling routines that the parameter in question will contain a value when the method returns, but there is no need to pass any value into the method when calling it.

    This might make a difference when parameters and return values needs to be packaged up and transported to the remote location where the actual call goes through.

    In other words, if you were to specify that on a method call used through P/Invoke, no marshalling will be done of the existing parameter value when the method is called, but when the method returns its value is lifted back into your calling code.

    Note that this optimization is up to the marshalling routine to use, or not, these are implementation details. The attribute just tells the routine which parameters it can do that with, it is not an instruction that will always be followed.