Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# changing a value with extension method

Tags:

c#

If I have the following extension methods:

internal static class Extensions
{
    public static void Increase(this uint value)
    {
        value += 1;
    }

    public static void Decrease(this uint value)
    {
        if (value > 0) value -= 1;
    }
}

Why does this not result in a changing i to 1?

uint i = 0;
i.Increase();
like image 537
Aaron Thomas Avatar asked Aug 31 '26 05:08

Aaron Thomas


1 Answers

The parameter is being passed by value, that's all. There's nothing special about extension methods on this front. It's equivalent to:

Extensions.Increase(i);

You'd need the method to have the first parameter passed by reference (with ref) for that to have any effect... and that's prohibited for extension methods anyway.

So while you could write a method allowing you to call it as:

Extensions.Increase(ref i);

you won't be able to make that an extension method.

An alternative is to make the method return a value, at which point you could have:

i = i.Increase();

If you're not entirely clear on pass-by-reference vs pass-by-value semantics, you might want to read my article on the topic.

like image 115
Jon Skeet Avatar answered Sep 01 '26 21:09

Jon Skeet