Search code examples
c#.netextension-methods

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


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?


Solution

  • 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.