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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With