Home >Backend Development >C++ >Can Ref and Out Modifiers Be Used in C# Extension Methods?
ref and out modifiers in C# extension methods
In an extension method that extends a reference type, the first parameter cannot use the ref
or out
modifier. However, starting with C# 7.2, it is possible to add the ref
modifier to the first parameter of an extension method of an extended value type (struct).
The reason for this limitation is that the first parameter of an extension method is considered a receiver parameter, which represents the instance being extended. For reference types, the receiver parameter is always passed by reference, so using the ref
or out
modifier is redundant.
However, for value types, the receiver parameter is passed by value, which means that any changes made to it in the extension method will not be reflected in the original value type instance. By using the ref
modifier, you can pass a value type instance by reference, allowing you to modify its state in an extension method.
Example:
<code class="language-csharp">public struct MyProperties { public string MyValue { get; set; } } public static class MyExtensions { public static void ChangeMyValue(this ref MyProperties myProperties) { myProperties.MyValue = "hello from MyExtensions"; } } public class MyClass { public MyClass() { MyProperties myProperties = new MyProperties(); myProperties.MyValue = "hello world"; myProperties.ChangeMyValue(); // Now modifies the original myProperties instance } }</code>
In this example, the ChangeMyValue
extension method can modify the state of the ref
value type instance using the MyProperties
modifier. Note that the out
modifier still cannot be used on the first parameter of an extension method.
The above is the detailed content of Can Ref and Out Modifiers Be Used in C# Extension Methods?. For more information, please follow other related articles on the PHP Chinese website!