When shouldn’t you write ref this?

Last time, we saw that the this parameter to an instance method in a struct is passed by reference, allowing the method to re-assign this or pass it as a ref parameter.

Due to limitations in the CLR, the this parameter to an iterator method is not a reference to the caller’s struct, and is instead a copy of the value.  Quoting the spec (§7.6.7)

  • When this is used in a primary-expression within an instance method or instance accessor of a struct, it is classified as a variable. The type of the variable is the instance type (§10.3.1) of the struct within which the usage occurs.
    • If the method or accessor is not an iterator (§10.14), the this variable represents the struct for which the method or accessor was invoked, and behaves exactly the same as a ref parameter of the struct type.
    • If the method or accessor is an iterator, the this variable represents a copy of the struct for which the method or accessor was invoked, and behaves exactly the same as a value parameter of the struct type.

To explain why, you’ll need to understand how iterators are compiled.  As Jon Skeet explains, an iterator method is compiled into a nested class that implements IEnumerable, with the original code transformed into a state machine.  This nested class has fields to store the method’s parameters (which includes this for instance methods) so that the iterator code can use them. 

This is why iterators cannot take ref parameters; the CLR cannot store a reference (as opposed to a reference type) in a field.  Therefore, the this parameter is passed to iterator methods by value, not by reference.
This is also why anonymous methods in structs cannot use this; anonymous methods are also compiled to methods in separate classes and so cannot inherit the ref parameter.

This means that if you change the Mutate method from before into an iterator, the code will still compile (!), but the calling method will not see the changes.

static void Main() {
    Mutable m = new Mutable();
    m.MutateWrong().ToArray();    //Force the iterator to execute
    Console.WriteLine("In Main(): " + m.Value);
}

struct Mutable {
    public int Value;
    
    public IEnumerable<int> MutateWrong() {
        this = new Mutable();
        MutateStruct(ref this); 
        Console.WriteLine("Inside MutateWrong(): " + Value);
        yield break;
    }
}
static void MutateStruct(ref Mutable m) { 
    m.Value++; 
}
This code prints
Inside MutateWrong(): 1
In Main(): 0
In summary, don’t mutate structs in iterators (or at all, if you can help it).
I don’t know why this isn’t a compiler error.

20 comments:

Thanks for telling this story. Viki

You will find here essay writing tips that could be really useful for your future work. I think it could be really helpful

I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. I think it may be help all of you. Thanks a lot for enjoying this beauty blog with me. I am appreciating it very much! Looking forward to another great blog. Good luck to the author! all the best!
Jugar aqui friv juegos gratis!

With technology development and its penetration into the previously conservative and expensive educational process, we have faced the inevitable step: the flourishing era of online education https://bestwritingservice.com/online-test-assistance.html.

Since everything is evolving more on the internet and people want little to do. I want to recommend you Here https://papermasters.org/buy-argumentative-essay-on-any-topic-online you can cope with homework and writing your essay. He tried and convinced himself!

Software testing training in Mumbai
nice blog
Software testing classes in Mumbai

Thanks for sharing such informative news.
Become Data science expert with Innomatics where you get a great experience and better knowledge.
Data Science course training in hyderabad

I've been following you for three years since you consistently bring amazing perspectives and thoughts. I'm a first-year university student that enjoys reading different blogs since they inspire me. I too use Pay To Take Online Class services that have provided me with excellent results.

Become a data science expert by joining AI Patasala’s Data Science Course in Hyderabad, where you can learn more about data science concepts with practical Knowledge.
Data Science Course Training in Hyderabad
Data Science Course Training Institute in Hyderabad

Great information! I thankful to author of this blog who sharing such a useful information,MBA assignment paper writer I also subscribe your blog for all future post. I also have share some useful links here.

This blog was a lot more fun for me. It's a fascinating topic. It greatly helped me in resolving several problems. Its opportunities are amazing, and its working style is lightning quick. I believe it will be helpful to business essay help UK of you. Thank you for time to read this beauty blog with me. It's very much welcomed! I'm looking forward to another great posting from you.

web application penetration testing for the best results, the automation is done while you logged-in account.

It is collected from different sources for different reasons, and then it is analyzed to make sense of data that the machines can interpret.
data science training in bhubaneswar

Thanks for sharing such informative news.
Need Visa Service Visit Migration & Visa Consultant Perth

A website's rating and visibility in search engine results pages are improved through the process of SEO, digimarketinginc.com or search engine optimisation. This entails a range of tactics to enhance both on-page and off-page components, with the ultimate objective of bringing more relevant visitors to the website.

Aside from poor thoughts of an employee's job or attitude, another cause for declining a reference might be a lack of confidence in your knowledge of their work. "You may not have had a direct reporting relationship, spa massage center in karachi but you developed a good working relationship within the company."

"2010When" is a valuable resource for writers, providing citation practices but may not be suitable for specialized or niche topics. It may be too detailed for quick consultations and may not be suitable for quick consultations. It's essential to balance the specific needs of your writing task with the depth of information provided. Abogado de Conducir Sin Licencia Condado de Hudson

โปรโมชั่น pg slot มากมาย เล่นง่ายจ่ายจริง แตกจริง ต้อง pg slot เท่านั้น! เล่นสล็อต พีจีสล็อต เว็บไซต์ตรงผู้ให้บริการเกมสล็อตออนไลน์ชั้นหนึ่ง ทกลอง เล่น ฟรี พร้อมโบนัส

Post a Comment