Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with the answers from Jon Skeet et al. about how allowing "ref this" extension methods could make the code more obscure. But if you look at some namespaces in the .Net Framework, it is common for a method invoked on a struct to alter it. </p> <p>Take for example the System.Drawing structs (Point, Rectangle, etc). Each of these has methods (e.g. Offset, Inflate, etc) that mutate the struct itself. I'm not saying this is a good idea, in fact I personally find it very annoying that Offset, Inflate, etc mutate the structs themselves instead of returning new ones, and I know some of you are opposed to the idea of mutable structs in general.</p> <p>I doubt there are any cases where invoking a method of a reference type will change the reference (unless it's with the <code>String</code> class, where I can imagine there might be some compiler magic to switch references to perform interning, etc). So it makes sense to prevent "this ref" from being used with reference types, because changing a reference would be a completely non-standard side-effect of calling a method. </p> <p>But in regards to structs, allowing "this ref" would not significantly decrease code readability any more than Rectangle.Inflate, etc, and it would provide the only means to "simulate" that kind of behavior with an extension function.</p> <p>Just as a side-note, here is one example where "this ref" <em>might</em> be useful, and IMHO still readable:</p> <pre><code>void SwapWith&lt;T&gt;(this ref T x, ref T y) { T tmp = x; x = y; y = tmp; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload