Search code examples
c#propertieslazy-initialization

Lazy dictionary properties in C#


I have a class with a property that's a Dictionary:

public class Entity 
{
    public Dictionary<string, string> Name { get; set; }
}

I would like switch this property to use lazy initializtion. I tried the following:

public class Entity 
{
    private Lazy<Dictionary<string, string>> name = new Lazy<Dictionary<string, string>>(() => new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
    public Dictionary<string, string> Name
    {
        get => name;
        set => name = value;
    }
}

This is of course an error, as Name and name have different types. For the life of me though, I can't figure out how to specify this correctly. All I really want is to have Name remain null until I access it, then create it on the first read or write.


Solution

  • You can use the initialization with Lazy, but what you want is pretty simple and you could simply do this

    private Dictionary<string, string> _name;
    public Dictionary<string, string> Name
    {
        get
        {
            if (_name == null)
                _name = new Dictionary<string, string>();
            return _name;
        }
        set _name = value;
    }
    

    EDIT: Note that this approach will have some thread safety issues. Check if this can be a problem for you.