Change value inside an (void) extension method

前端 未结 6 1017
心在旅途
心在旅途 2021-02-12 23:28

So I have this mock extension method which change a value to another value:

public static void ChangeValue(this int value, int valueToChange)
{
    value = value         


        
6条回答
  •  囚心锁ツ
    2021-02-13 00:10

    Old question, but on newer versions of C# it looks like you can now do this for value types by using the this and ref keywords together. This will set value to be the same as valueToChange, even outside of this extension method.

    public static void ChangeValue(this ref int value, int valueToChange)
    {
        value = valueToChange;
    }
    

    I believe this change was made to the compiler on version 15.1, which I think corresponds to C# 7 (or one of its sub versions). I did not immediately find a formal announcement of this feature.

提交回复
热议问题