When can you write ref this?

Usually, you cannot pass ref this as a parameter, since this is not a writable field.  However, that’s not true for value types.  The this field of a value type is a writable value.

To quote the spec (§5.1.5)

Within an instance method or instance accessor of a struct type, the this keyword behaves exactly as a reference parameter of the struct type (§7.6.7).

Therefore, the following code prints 1:

static void Main() {
    Mutable m = new Mutable();
    m.Mutate();
    Console.WriteLine(m.Value);
}

struct Mutable {
    public int Value;
    
    public void Mutate() {
        this = new Mutable(); 
        MutateStruct(ref this); 
    }
}
static void MutateStruct(ref Mutable m) { 
    m.Value++; 
}

In practice, this should never come up, since mutable structs are evil and should be avoided at all costs.

Next time: This doesn’t always work.

0 comments:

Post a Comment