What is wrong with??? statement used as follows:

Thus, the entry:

if (obj.Collection == null) obj.Collection = new Collection(); obj.Collection.Add(something); 

I thought to write:

 obj.Collection = obj.Collection ?? new Collection; obj.Collection.Add(something); 

This seems wrong, especially this part of "obj.Collection = obj.Collection ..."

What do you guys think?

Hi,

+7
source share
4 answers

If I had to choose between these two blocks of code, I would use the first. This is more readable and this is a common template. ?? useful in scenarios where you need to set a default value (e.g. DateTime date = nullableDateTimeInstance ?? defaultDate; ).

But to be honest, I’ll try not to be in a situation where I want to add to the collection, and perhaps the collection will be zero. Instead, I would make sure that the collection is initialized in the constructor or whatever.

+15
source

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); 
+3
source

The code produces an unnecessary assignment (obj.Collection for itself) if obj.Collection is not null, but differs from it equivalent to the original.

It looks good if you do not use it in temporary critical sections. In any case, it may be that the compiler can optimize the assignment, but I don’t know if it will be.

Perhaps it just doesn’t feel right, because the source code is so common and simple that it’s wrong to change it.

0
source

I would say that this also depends on what the setter of the Collection property does. Consider this:

 public Collection Collection { get { return _collection; } set { _collection = value; Thread.Sleep( 1000 ); // or some expensive real work } } 

In this case, the assignment obj.Collection = obj.Collection ?? new Collection() obj.Collection = obj.Collection ?? new Collection() will be really expensive.

However, if you need to create a collection "on demand", usually use a similar template in the getter properties, for example:

 public Collection Collection { get { return _collection ?? ( _collection = new Collection() ); } } 
0
source

All Articles