[ACCEPTED]-How can I get an extension method to change the original object?-extension-methods

Accepted answer
Score: 42

You have to modify the contents of the List<string> passed 2 to the extension method, not the variable 1 that holds the reference to the list:

public static void ForceSpaceGroupsToBeTabs(this List<string> lines)
{
    string spaceGroup = new String('.', 4);
    for (int i = 0; i < lines.Count; i++)
    {
        lines[i] = lines[i].Replace(spaceGroup, "T");
    }
}
Score: 17

You'd have to change the contents of the original 16 list - just reassigning the parameter to 15 have a different value isn't going to do 14 it. Something like this:

public static void ForceSpaceGroupsToBeTabs(this List<string> lines)
{
    string spaceGroup = new String('.', 4);
    for (int i = 0; i < lines.Count; i++)
    {
        lines[i] = lines[i].Replace(spaceGroup, "T");
    }
}

It's worth noting 13 that this has nothing to do with extension methods. Imagine you'd just called:

Helpers.ForceSpaceGroupsToBeTabs(lines);

... because 12 that's what the code is effectively translated 11 into. There's nothing special about the 10 fact that it's an extension method; if you 9 change the code so that the "normal" static 8 method will work, then it'll work as an 7 extension method too. As noted in the comments, one 6 thing you can't do with an extension method is 5 make the first parameter a ref parameter.

(EDIT: I 4 realise this is the exact same code that 3 dtb posted, although we arrived there independently. I'm 2 keeping this answer anyway, as it's got 1 more than code.)

Score: 15

If it's a reference type, you'd have to 11 change it's contents. If it's a value type 10 you're passing in, you're out of luck. The 9 very existence of extension methods is put 8 into place to support functional paradigms 7 in C#, and those functional paradigms, by 6 their very essence, tend towards immutability 5 of types, hence the inability to change 4 the value off of which the extension method 3 is called.

In other words, while you could do 2 it, it may not be in keeping with the "spirit" of 1 functional programming.

More Related questions