Doesn't C# Extension Methods allow passing parameters by reference?

前端 未结 3 1155
庸人自扰
庸人自扰 2020-12-03 17:19

Is it really impossible to create an extension method in C# where the instance is passed as a reference?

Here’s a sample VB.NET console app:

Imports          


        
3条回答
  •  长情又很酷
    2020-12-03 17:34

    No. In C#, you cannot specify any modifiers (like 'out' or ref) other than this for the first parameter of an extension method - you can for the others. Not familiar with the VB Syntax but it seems to be using a declarative approach to mark an extension method.

    When you call it, you do not specify the first this parameter. Hence marking the parameter as out or ref doesnt make sense as You can't specify the modifier when you call it like you'd do for normal methods

    void MyInstanceMethod(ref SomeClass c, int data) { ... } // definition
    
    obj.MyInstanceMethod(ref someClassObj, 10);              // call
    
    void MyExtensionMethod(this SomeClass c, int data) {.... } // defn
    
    c.MyExtensionMethod(10);                                 // call
    

    I think the trouble you're having here is related to value types being immutable. If Weekdays was a reference type, it would work out alright. For immutable types (structs), the defacto way is to return a new instance with the required value. E.g. See the Add method on the struct DateTime, it returns a new DateTime instance whose value = receiver DateTime instance's value + param value.

    public DateTime Add( TimeSpan value )
    

提交回复
热议问题