False Dictionary Properties in C #

I have a class with the property that the dictionary:

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

I would like to switch this property to use lazy initialization. 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 { return name; } set { name = value; } } } 

This, of course, is a mistake, since the name and the name have different types. For the life of me, however, I cannot figure out how to indicate this correctly. All I really want is to have a name that stays null until I get access to it, and then create it the first time I read or write it.

+8
c # properties lazy-initialization
source share
2 answers

You can use initialization with Lazy , but what you want is pretty simple, and you could just do it

  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: Please note that this approach will have some thread safety issues. Check if this could be a problem for you.

+10
source share

name.Value is read-only. Try 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 { return name.Value; } } } 
+7
source share

All Articles