Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 950
Hun1Ahpu Avatar asked Apr 11 '10 20:04

Hun1Ahpu


People also ask

What is correct extension method?

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.

What are extension methods in LINQ?

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.

What is the role of an extension method when would you use it?

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.

How does the ref modifier change a function or method parameter?

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.


2 Answers

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.

like image 102
Jon Skeet Avatar answered Oct 13 '22 22:10

Jon Skeet


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

like image 25
juliushuck Avatar answered Oct 14 '22 00:10

juliushuck