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?
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
Extension Methods are a new feature in C# 3.0, and they're simply user-made pre-defined functions. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modifying the original types.
Extension methods enable developers to add custom functionality to data types that are already defined without creating a new derived type. Extension methods make it possible to write a method that can be called as if it were an instance method of the existing type.
The ref Modifier By default, a reference type passed into a method will have any changes made to its values reflected outside the method as well. If you assign the reference type to a new reference type inside the method, those changes will only be local to the method.
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.
In C# 7.2 you can use ref extension methods for structs
See https://github.com/dotnet/csharplang/issues/186 and https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/readonly-ref.md
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With