Prometheus
Prometheus

Reputation: 56

How to use a c# extension method to add to list as well as create the list

When I use the below method, when this list is null, the list is created and a record is added, but the list is still null outside of the method.

However if the list is already created then I see the list grow outside the method.

    public static void Add(this List<Setting> Settings, object Name, object Value)
    {
        if(null==Settings)
        {
            Settings = new List<Setting>();
        }

        var item = Settings.FirstOrDefault(s => s.Name.ToLower() == Name.ToString().ToLower());
        if (null != item)
        {
            //overwrite the value of an existing item
            item.Value = Value.ToString();
        }
        else
        {
            //Add the new Setting to the list
            Settings.Add(new Setting(Name.ToString(), Value.ToString()));
        }
    }

Upvotes: 0

Views: 144

Answers (2)

moarboilerplate
moarboilerplate

Reputation: 1643

An extension method is not the way to go here. Reassigning an object reference should never be the duty of the object itself. That should be the responsibility of the caller/consumer of the object.

Upvotes: 1

Jakub Lortz
Jakub Lortz

Reputation: 14896

This is the way arguments are passed to methods in C#. The Settings is a copy of the references you called the extension method on. It points to the same object, but it's a different reference. So if you assign a new value to it, the outer reference remains unchanged.

You might consider changing the return type from void to List<Settings>.

Then you can use:

settings = settings.Add(name, value);

Additional benefit is ability to chain Add:

settings = settings.Add(name1, value1)
                   .Add(name2, value2)
                   .Add(name3, value3);

Upvotes: 1

Related Questions