Impossible to use ref and out for first ("this") parameter in Extension methods?

Hun1Ahpu picture Hun1Ahpu · Apr 11, 2010 · Viewed 12k times · Source

Why is it forbidden to call Extension Method with ref modifier?

This one is possible:

public static void Change(ref TestClass testClass, TestClass testClass2)
{
    testClass = testClass2;
}

And this one not:

public static void ChangeWithExtensionMethod(this ref TestClass testClass, TestClass testClass2)
{
    testClass = testClass2;
}

But why?

Answer

Jon Skeet picture Jon Skeet · Apr 11, 2010

You have to specify ref and out explicitly. How would you do this with an extension method? Moreover, would you really want to?

TestClass x = new TestClass();
(ref x).ChangeWithExtensionMethod(otherTestClass);
// And now x has changed?

Or would you want to not have to specify the ref part, just for the first parameter in extension methods?

It just sounds weird to me, to be honest, and a recipe for unreadable (or at least hard-to-predict) code.