views:

61

answers:

2

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?

A: 

This would mean that calling myObject.ChangeWithExtentionMethod(otherObject) would actually have the potential to change myObject's value. IMO, that wouldn't make for very readable code when you can instead achieve the desired effect by using a regular non-extension method with a ref.

EDIT: My point is, the method call should require you to use the ref keyword any time that you're passing something by reference. Using ref with an extension method's 'this' parameter would violate that behavior.

nonoitall
+5  A: 

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.

Jon Skeet
But that reason no longer applies for C# 4. In fact, in VB you *can* already use `ByRef` extension methods, if I remember correctly.
Konrad Rudolph
"You have to specify ... explicitly" is an artificial compiler requirement that could be dropped here. That would make it even more obscure though.
Henk Holterman
@Konrad: It only doesn't apply in C# 4 for COM methods. @Henk: Yes, it's 'artificial' - but for the sake of readability. I think it's an entirely reasonable restriction.
Jon Skeet