C# changing a value with extension method

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();
Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow