I need to take a Widget that already has several property values set. I need to change the Widget's name. I'm drawn toward Option 3, but I'm having a hard time articulating why.
public void Do(Widget widget) { // 1
widget.Name = "new name";
}
public void Do(ref Widget widget) { // 2
widget.Name = "new name";
}
public Widget Do(Widget widget) { // 3
widget.Name = "new name";
return widget;
}
I'd like to play Devil's Advocate with a few questions and gather responses, to help me explain why I'm drawn to Option 3.
Option 1 : Why not just modify the Widget that's passed in? You're only "returning" one object. Why not just use the object that's passed in?
Option 2 : Why not return void? Why not just communicate in the signature that you'll be using the actual memory pointer to the parameter object itself?
Option 3 : Isn't it weird to you that you're returning the same object you're passing in?
ref
in the second option is entirely superflous. – Miceliwidget
, not one of its properties, but I think Option 2, as it's shown, reflects the confusion that many developers (myself perhaps included, at times) have about the proper use of theref
keyword. – Teenyweeny