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.
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.
I doubt there are any cases where invoking a method of a reference type will change the reference (unless it's with the String
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.
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.
Just as a side-note, here is one example where "this ref" might be useful, and IMHO still readable:
void SwapWith<T>(this ref T x, ref T y) {
T tmp = x; x = y; y = tmp;
}
ref
is necessary? I would expect that it is "auto-generated" bythis
- non-reference extension methods wouldn't make any sense. – Gogh