Reference type still needs pass by ref?

Everything is passed by value in C#. However, when you pass a reference type, the reference itself is being passed by value, i.e., a copy of the original reference is passed. So, you can change the state of object that the reference copy points to, but if you assign a new value to the reference you are only changing what the copy points to, not the original reference.

When you use the ‘ref’ keyword it tells the compiler to pass the original reference, not a copy, so you can modify what the reference points to inside of the function. However, the need for this is usually rare and is most often used when you need to return multiple values from a method.

An example:

class Foo
{
    int ID { get; set; }

    public Foo( int id )
    {
        ID = id;        
    }
}

void Main( )
{
    Foo f = new Foo( 1 );
    Console.WriteLine( f.ID );  // prints "1"
    ChangeId( f );
    Console.WriteLine( f.ID );  // prints "5"
    ChangeRef( f );
    Console.WriteLine( f.ID );  // still prints "5", only changed what the copy was pointing to
}

static void ChangeId( Foo f )
{
    f.ID = 5;
}

static void ChangeRef( Foo f )
{
    f = new Foo( 10 );
}

Leave a Comment