Consider the following code snippet( written in a Windows Form Application):
public partial class Form1
{
....
public void Caller()
{
Form1 myRef = this;
Change(ref this) //--> won't compile because *this* is read-only
Change(ref myRef); //--> compiles but doesn't work.
}
....
public void Change(ref Form1 theRef)
{
theRef = new Form1();
theRef.Text = "I am a new form";
}
}
Passing this by reference is not allowd. That's ok and sensible. But why passing this indirectly as shown above is not working? As I know if a parameter is passed by reference any assignment in the called method is reflected out to the caller method. Why isn't it working here?
Update to make the question clear
1- I am not struggling to accomplish anything special. I am just trying to test ref.
2- The reason why I misunderstood the ref is that I totally forgot Form1 myRef = this actually copies the address of underlying Form1 object to myRef; so myRef variable has nothing to do with this except that both of them points to the same object.
It works as it should. The problem is that this is not the same as what you are expecting.
Form1 myRef = this;
var b1 = object.ReferenceEquals(myRef, this); // true
Change(ref myRef);
var b2 = object.ReferenceEquals(myRef, this); // false
So the value of myRef changes. That the change does not propagate to this should be expected; after making the assignment myRef and this are totally separate variables. C# does not have "ref variables", so it couldn't be any other way (even if it had, reassigning this in this manner would never be allowed).
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