简体   繁体   中英

Assigning auto-implemented property to itself with null coalescing operator “??”

I have an auto-implemented property which takes the default value. This property reads its value from a database, but if that's null it should take its default value.

    // Variable Declaration
    public bool IsSoundEffects { get; set; } = true;

    // Usage
    bool? readFromDB = null;    // Get it from Database assume its NULL
    IsSoundEffects = readFromDB ?? IsSoundEffects;

Is assigning IsSoundEffects to itself a usual practice if a previous database read results in null?

What should do the trick to make this code organized and readable?

What you are doing is fine. As an alternative, GetValueOrDefault will also work.

IsSoundEffects = readFromDb.GetValueOrDefault(IsSoundEffects);

Either of these are good solutions if your readFromDb was really a method with parameters because you can have clean syntax such as the below

IsSoundEffects = readFromDb(some, parameters).GetValueOrDefault(IsSoundEffects);
IsSoundEffects = readFromDb(some, parameters) ?? IsSoundEffects;

The former was your only option prior to the ?? operator being introduced into C#.

If the "assign to self" is distasteful, then avoid the initial assignment, and do it explicitly elsewhere, eg

public bool IsSoundEffects { get; set; }
...
IsSoundEffects = readFromDb(some, parameters).GetValueOrDefault(true);
IsSoundEffects = readFromDb(some, parameters) ?? true;

Make it simple

if(readFromDB != null) IsSoundEffects = readFromDB;

So that you can avoid the assignment of same value when readFromDB is null.

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