简体   繁体   中英

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

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 (eg, 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);

The code will emit an unnecessary assignment (of obj.Collection to itself) if obj.Collection is not null, but other than that it is equivalent to the original.

Looks fine to me provided you don't use it in time critical sections. Anyway it's possible the compiler can optimise the assignment away, but I don't know if it would or not.

Perhaps it just feels wrong because the original code is such a common and simple pattern that it feels wrong to change it.

I'd say it 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() would be really costly.

However, if you need to create a collection "on demand", it's common to use a similar pattern in the property getter, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM