Change value inside an (void) extension method

前端 未结 6 1023
心在旅途
心在旅途 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:05

    int is a struct so it's a value-type. this means that they are passed by value not by reference. Classes are reference-types and they act differently they are passed by reference.

    Your option is to create static method like this:

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

    and use it:

    int a = 10;
    ChangeValue(ref a, 15);
    

提交回复
热议问题