Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do workaround to pass property by ref? Plus passing by ref incidences [closed]

Is it possible to do workaround for Automatic property of Reference Type (Class) to be able passed by Ref?

The only thing I think about is not to use Automatic property: just declare private variable as always and passing it by ref + adding public property aside if I need.
Frankly it looks a bit stupid ( all that bureaucracy needed to bypass it)

My Questions:
1.Why the compiler don't allow automatic property to be pass by ref(like it was a simple data member)? 2.When do we use or should use Ref? I noticed some people saying that using it may occur only in rare scenarios. What are them?

like image 341
JavaSa Avatar asked Dec 11 '25 15:12

JavaSa


1 Answers

Why the compiler don't allow automatic property to be pass by ref

because it's not a reference - it's a method pair (get/set). The workaround is to create a local variable that hold's the property's value, pass that by reference, and set the property to the updated value:

var temp = myObj.myProperty;
MethodWithRefParam(ref temp);
myObj.MyProperty = temp;

As you said, you could pass the backing property by reference, but only from within that class.

When do we use or should use Ref?

Typically ref (and out, which is a special case of ref) parameters are only used when returning the value is not practical. TryParse is a common framework example. Instead of returning the parsed value, the method returns a bool telling you whether the parse succeeded or not, and "returns" the parsed value in an out parameter.

Using ref with reference types is usually a code smell that could indicate the author doesn't understand how reference types work.

like image 200
D Stanley Avatar answered Dec 14 '25 03:12

D Stanley