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,
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.
The SQL LIKE and NOT LIKE operators are used to find matches between a string and a given pattern. They are part of standard SQL and work across all database types, making it essential knowledge for all SQL users.
The OR operator is used in most programming languages which support logical and comparison operators. In the programming world, it is mainly used to control the flow in programs, similar to other logical operators. It is also an important component while setting up digital circuit logic.
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.
Do you mean:
if (obj.Collection == null)
{
obj.Collection = new Collection();
}
obj.Collection.Add(something);
If so, you can rewrite it as
(obj.Collection = (obj.Collection ?? new Collection())).Add(something);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With