What is the best way to modify and return a C # argument?

I need to take a widget that already has several property values. I need to change the name of the widget. I turned to Option 3, but it's hard for me to understand 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 would like to play Devil Advocate with a few questions and collect answers to help me explain why Option 3 attracts me.

Option 1: Why not just change the widget that went through? You only "return" one object. Why not just use the object that passed?

Option 2: Why not return void? Why not just mess in the signature that you will use the actual memory pointer for the parameter object itself?

3: , , ?

+5
4

1:. - ref, . , , , .

2: , , .. Widget , ( , , , . " " , factory). .

3: "" - , .. , . .

+12

1:

Fine. , . , .

2:

. . . , ref. (, widget = new Widget(), out/ref - , .

3:
1. API. . , .


, . , .

4: . , , , , .

+6

. ( , , .) - 1.

+4

, 1 3 . 3 , , . , 2. ref , , , , .

+1

All Articles