So insteed of writing:
if (obj.Collection == null)
obj.Collection = new Collection();
obj.Collection.Add(something);
I thought of writing:
obj.Collection = obj.Collection ?? new Collection;
obj.Collection.Add(something);
It kind of feels wrong, especially this part “obj.Collection = obj.Collection…”
What do you guys think ?
Regards,
If I had to choose between these two blocks of code, I would use the former. It’s more readable and it’s a common pattern.
??is useful in scenarios where you need to default a value (e.g.,DateTime date = nullableDateTimeInstance ?? defaultDate;).But frankly, I’d try to not end up in situation where I want to add to collection and it’s possible that the collection is null. Instead, I’d make sure that the collection is initialized in the constructor or whatever the case may be.