Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a ref Parameter with the this Keyword?

Is there a way to force the this keyword to act as a ref argument? I would like to pass in a visitor that modifies multiple properties on the object, but this only wants to act like a value parameter.

Code in Object:

public void Accept(Visitor<MyObject> visitor)
{
    visitor.Visit(this);
}

Code in Visitor:

public void Visit(ref Visitor<MyObject> receiver)
{
    receiver.Property = new PropertyValue();
    receiver.Property2 = new PropertyValue();
}
like image 235
grefly Avatar asked Apr 15 '10 16:04

grefly


2 Answers

Since you are not actually changing what receiver refers to there is no need for the ref keyword. However, if that would have been the case, you would not be able to make this refer to another instance.

In order to pass this as a ref parameter, you would need to write it like this:

Visit(ref this);

That code will not compile: "Cannot pass '<this>' as a ref or out argument because it is read-only"

like image 132
Fredrik Mörk Avatar answered Oct 20 '22 03:10

Fredrik Mörk


If your Visitor<T> is a class, then you don't need the ref keyword.

All the info inside a class is automatically changed if they are changed in a method

like image 25
Graviton Avatar answered Oct 20 '22 02:10

Graviton