Randy
Randy

Reputation: 1287

What is the advantage of using the ref keyword with a reference type parameter?

What do I gain, as the developer, by passing a reference type argument to a method using the ref keyword if you are not changing what the reference points to?

I have read both, ref keyword with reference type parameter and What is the use of "ref" for reference-type variables in C#? and a number of others. I am aware this subject has been asked about and answered a great number of times. I believe I am asking a unique question. Feel free to mark down my question if you know other wize.

Simple class:

public class Person
{
    public Person(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1}", FirstName, LastName);
    }
}

Form passing using keyword ‘ref’:

public partial class Form2 : Form
{
    private Person _person;

    public Form2()
    {
        _person = new Person("John", "Doe");
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        textBox1.Text = _person.ToString();

        base.OnLoad(e);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ChangeLastName(ref _person);

        textBox2.Text = _person.ToString();
    }

    private static void ChangeLastName(ref Person person)
    {
        person.LastName = "Smith";
    }
}

Form passing parameter without using keyword ‘ref’:

public partial class Form2 : Form
{
    private Person _person;

    public Form2()
    {
        _person = new Person("John", "Doe");
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        textBox1.Text = _person.ToString();

        base.OnLoad(e);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ChangeLastName(_person);

        textBox2.Text = _person.ToString();
    }

    private static void ChangeLastName(Person person)
    {
        person.LastName = "Smith";
    }
}

What is the difference if any or what as a developer do I gain from the former (other than the ability to new up the passed parameter inside my method)?

Thanks in advance,

Upvotes: 0

Views: 1077

Answers (1)

D Stanley
D Stanley

Reputation: 152626

What do I gain, as the developer, by passing a reference type argument to a method using the ref keyword if you are not changing what the reference points to?

None whatsoever - that's the only purpose of passing a reference type by reference is if you are going to change what the reference refers to.

To be fair - it gives you the ability to change that behavior in the future, which would be sadistic and cruel...

Upvotes: 8

Related Questions