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:
- Use immutable implementation; I doubt if we want to change
Id
once instance has been created; probably, the same is forPersonProperties
. - Do not expose
set
for collection: why should we allow toset
, say,null
to the property? - We may want to be nice, and let key be case insensitive
- We should validate constructor's input
- 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);
}
}