Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with the ?? operator used like this:

Tags:

c#

coalesce

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,

like image 955
Calin Avatar asked Jan 23 '11 19:01

Calin


People also ask

What is the LIKE operator used for?

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.

What do the like and not like operators do?

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.

Why or operator is used?

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.


2 Answers

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.

like image 115
jason Avatar answered Oct 26 '22 08:10

jason


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);
like image 38
tenor Avatar answered Oct 26 '22 09:10

tenor