Search code examples
c#.netpass-by-referencerefreference-type

"ref" keyword and reference types


someone in my team stumbled upon a peculiar use of the ref keyword on a reference type

class A { /* ... */ } 

class B
{    
    public void DoSomething(ref A myObject)
    {
       // ...
    }
}

Is there any reason someone sane would do such a thing? I can't find a use for this in C#


Solution

  • Let

    class A
    {
        public string Blah { get; set; }
    }
    
    void Do (ref A a)
    {
        a = new A { Blah = "Bar" };
    }
    

    then

    A a = new A { Blah = "Foo" };
    Console.WriteLine(a.Blah); // Foo
    Do (ref a);
    Console.WriteLine(a.Blah); // Bar
    

    But if just

    void Do (A a)
    {
        a = new A { Blah = "Bar" };
    }
    

    then

    A a = new A { Blah = "Foo" };
    Console.WriteLine(a.Blah); // Foo
    Do (a);
    Console.WriteLine(a.Blah); // Foo