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.

7 comments:

This publication is excellent. Rose

I am sure that advices from https://resumecvwriter.com/blog/how-to-write-resume-job-description will help you to write your resume job description. I had such experience so I know what I am talking about

Thanks for your article! I have been looking for quite a long time and fortunately I read this article! I wish you would continue to have valuable articles like this or more to share with everyone
Joaca acum gratis jocuri friv!

There are hundreds of engineering college in India but top private engineering colleges in up to 2020 listed are some colleges and which are selected on the basis of some parameters like technical training for the students, In this the best is NSMX is a market research services and consulting company affianced in providing an integrated solution to a wide range of small, medium & large online market research companies seeking services throughout the world. NSMX has established brand equity in the Market Research domain through the range of services provided to its client base and the domain knowledge of its professionals.. As well as in management colleges some best private MBA colleges in Delhi NCR available

Post a Comment