Pratik Deoghare
Pratik Deoghare

Reputation: 37172

C# ref question again?

 class Foo
    {
        public int A { get; set; }
    }

class Program
{
    static void Main(string[] args)
    {
        var f = new Foo();
        var ff = f;

        Console.WriteLine(f.GetHashCode());
        Console.WriteLine(ff.GetHashCode());

        FooFoo(ref f);
        BarBar(f);
    }

    private static void BarBar(Foo f)
    {
        Console.WriteLine(f.GetHashCode());
    }

    private static void FooFoo(ref Foo f)
    {
        Console.WriteLine(f.GetHashCode());
    }
}

OUTPUT:

58225482
58225482
58225482
58225482

What is the difference between FooFoo and BarBar?

Upvotes: 2

Views: 115

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391336

No effective difference in this case.

The point of ref is not to pass a reference to an object, it is to pass a reference to a variable.

Consider the following change:

private static void BarBar(Foo f)
{
    Console.WriteLine(f.GetHashCode());
    f = new Foo();
}

private static void FooFoo(ref Foo f)
{
    Console.WriteLine(f.GetHashCode());
    f = new Foo();
}

In this case, the FooFoo's change will also change the f variable in the Main method, but the BarBar method is only changing a local variable.

All reference types are passed as reference types in any case, you cannot change that. The only point to ref is to allow the called method to change the variable it is being passed.

Upvotes: 6

Related Questions