Home > Mobile >  Dictionary as the class property and argument to a method
Dictionary as the class property and argument to a method

Time:10-26

public class Person
{
    public int ID { get; set; }
    public Dictionary<string, string> PersonProperties { get; set; }

    public Person(int id, Dictionary<string, string>personInfo )
    {
        ID = id;
        PersonProperties = personInfo;

        foreach (KeyValuePair<string, string> kvp  in PersonProperties)
        {
            Console.WriteLine(kvp.Value);
        }

    }
}

In the above example, do I need to initialize the class property PersonProperties?

something like

public Dictionary<string, string> PersonProperties { get; set; } = new Dictionary<string, string>(); 

If yes, Why?

CodePudding user response:

I suggest a bit different implementation:

  1. Use immutable implementation; I doubt if we want to change Id once instance has been created; probably, the same is for PersonProperties.
  2. Do not expose set for collection: why should we allow to set, say, null to the property?
  3. We may want to be nice, and let key be case insensitive
  4. We should validate constructor's input
  5. Let's extract UI (Console.WriteLine) from Business Logic (constructor)
    public class Person {
      private readonly Dictionary<string, string> m_PersonProperties =
        new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

      public int ID { get; }
      
      // If we want to allow PersonProperties editing put it as
      // public IDictionary<string, string> ...
      public IReadOnlyDictionary<string, string> PersonProperties => 
        m_PersonProperties;

      public Person(int id, IEnumerable<KeyValuePair<string, string>> personInfo) {
        if (null == personInfo)
          throw new ArgumentNullException(nameof(personInfo));

        ID = id;

        foreach (var pair in personInfo)
          m_PersonProperties.TryAdd(pair.Key, pair.Value);
      }

      public void Print() {
        foreach (KeyValuePair<string, string> kvp in PersonProperties)
          Console.WriteLine(kvp.Value);
      }
    }
  • Related