Search code examples
c#out

'out' modifier in C#


Possible Duplicate:
C# - Reference type still needs pass by ref?

class OutReturnExample
{
    static void Method(out int i, out string s1, out string s2)
    {
        i = 44;
        s1 = "I've been returned";
        s2 = null;
    }
    static void Main()
    {
        int value;
        string str1, str2;
        Method(out value, out str1, out str2);
        // value is now 44
        // str1 is now "I've been returned"
        // str2 is (still) null;
    }

I am new to C# and learning out modifier. I came across this snippet on MSDN.

I understand out is useful here for int primitive variable, but for string variables, references will be passed to the called method even without the out modifier, right?


Solution

  • references will be passed to the called method even without the out modifier, right?

    Yes, but without out they will not be passed back:

    void M(string s1, out string s2)
    {
        s1 = "one";
        s2 = "two";
    }
    
    void Main()
    {
        string s = "hello", t = "world";
        // s = "hello"
        // t = "world"
        M(s, out t);
        // s = "hello"
        // t = "two"
    }
    

    string is designed as immutable. You are probably thinking about mutable reference types:

    class Person { public string Name { get; set; } }
    
    void Main()
    {
        var p = new Person { Name = "Homer" };
        // p != null
        // p.Name = "Homer"
        M2(p);
        // p != null
        // p.Name = "Bart"
    }
    
    void M2(Person q)
    {
        q.Name = "Bart";   // q references same object as p
        q = null;          // no effect, q is a copy of p
    }