How can I get an extension method to change the original object?

Edward Tanguay picture Edward Tanguay · Feb 24, 2010 · Viewed 16.5k times · Source

I want to be able to write extension methods so that I can say:

lines.ForceSpaceGroupsToBeTabs();

instead of:

lines = lines.ForceSpaceGroupsToBeTabs();

However, the following code currently outputs:

....one
........two

instead of:

Tone
TTtwo

What do I have to change in the following code to make it output:

Tone
TTtwo

(note that for visibility, . = space, T = \t):

using System;
using System.Collections.Generic;

namespace TestExtended82343
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lines = new List<string>();
            lines.Add("....one");
            lines.Add("........two");

            lines.ForceSpaceGroupsToBeTabs();

            lines.ForEach(l => Console.WriteLine(l));
            Console.ReadLine();
        }
    }

    public static class Helpers
    {
        public static void ForceSpaceGroupsToBeTabs(this List<string> originalLines)
        {
            string spaceGroup = new String('.', 4);
            List<string> lines = new List<string>();
            foreach (var originalLine in originalLines)
            {
                lines.Add(originalLine.Replace(spaceGroup, "T"));
            }
            originalLines = lines;
        }
    }
}

Answer

dtb picture dtb · Feb 24, 2010

You have to modify the contents of the List<string> passed to the extension method, not the variable 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");
    }
}