I’m trying to write safeAdd extention function for List class, so if it’s not initialized yet – initialize it and add new value. But after I return from extension method, my just initialized list equals null. What’s wrong?
Test class:
private class Test
{
public Test()
{
Id = Guid.NewGuid();
//items = new List<string>();
}
public Guid Id { get; set; }
public List<string> items { get; set; }
}
Extensions class:
public static class Helpers
{
public static void safeAdd<T>(this List<T> list, T item)
{
if (list == null)
list = new List<T>();
list.Add(item);
}
}
Part of main:
Test t = new Test();
t.items.safeAdd("testWord");
//Here t.items == null; WHY?
You have only assigned to a local method variable (which exists only inside the extension method) – this doesn’t do anything to invoke the
set, and to be honest there’s no convenient way to get access to both thegetandsetwithout being verbose, or using lots of reflection /Expressioncode. IMO just do it in the class:This will automatically initialize and assign the list the first time it is accessed.
It wouldn’t be thread-safe unless I sync’d, or (perhaps preferable) used
Interocked.CompareExchangefor the assign. View Interlockedit could be made thread-safe easily enough, but this is rarely a requirement for instance methods, and has associated overhead