Search code examples
c#.netkeywordout

Using the "out" keyword in C#


Can anyone tell me the exact usage of the "out" keyword as a paramter, and how its connected to returning multiple values from a function, as in the Return multiple values to a method caller post.

I am confused with the "out" variable vs a normal variable.


Solution

  • This is frequently confusing, and I think the MSDN documentation actually is a bit "clear only if already known". That is, it is correct, but it really only makes sense if you already understand the concept.

    Here's how I think of it.

    A regular parameter makes a copy of the value of the argument. When you say:

    static int M(int z) { z = z + 1; return z; }    
    ...
    int x = 123;
    int y = M(x);
    

    That is just like you said:

    int x = 123;
    int z = x; // make a copy of x
    z = z + 1;
    int y = z;
    

    A ref or out parameter make an alias for an existing variable. When you say

    static void N(ref int q) { q = q + 1; }    
    ...
    int x = 123;
    N(x);
    

    That is the same as saying:

    int x = 123;
    // MAGIC: q is now an another name for variable x
    q = q + 1;
    

    q and x are two different names that refer to the same variable. Incrementing q also increments x because they are the same. z and x in the previous example are two different names that refer to two different variables. Incrementing z does not change x.

    Summing up: "out" and "ref" just mean "do not make a new variable; rather, temporarily make a second name for an existing variable".

    Is that now clear?

    UPDATE: I did not say what the difference between "out" and "ref" is. The difference is simple. On the "caller" side, a "ref" must be a definitely assigned variable before the method is called. An "out" need not be. On the "callee" side, a "ref" may be read before it is written to, but an "out" must be written to before it is read. Also, an "out" must be written to before control leaves the method normally.