Why use the ‘ref’ keyword when passing an object?

If I am passing an object to a method, why should I use the ref keyword? Isn’t this the default behaviour anyway?

For example:

class Program
{
    static void Main(string[] args)
    {
        TestRef t = new TestRef();
        t.Something = "Foo";

        DoSomething(t);
        Console.WriteLine(t.Something);
    }

    static public void DoSomething(TestRef t)
    {
        t.Something = "Bar";
    }
}


public class TestRef
{
    public string Something { get; set; }
}

The output is “Bar” which means that the object was passed as a reference.

10 Answers
10

Leave a Comment