Reputation: 1287
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
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