SLaks.Blog

Making the world a better place, one line of code at a time

When can you write ref this?

Posted on Wednesday, December 22, 2010, at 8:50:00 PM UTC

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.

Categories: value-types, C#, .Net Tweet this post

comments powered by Disqus