简体   繁体   中英

Null Coalesce with colors

protected override void OnEnter(EventArgs e)
    {
        // this.Font = new Font(this.Font, FontStyle.Italic);
        base.BackColor = _colors.SelectedBackColor ?? base.BackColor;
        base.ForeColor = _colors.SelectedForeColor ?? base.BackColor;
        base.OnEnter(e);
    }

The error I get is

Error 519 Operator '??' cannot be applied to operands of type 'System.Drawing.Color' and 'System.Drawing.Color'

I thought it had to be 2 matching type for a null coalesce

Color is a struct and therefor can never be null. That is why you are getting the error.

Null coalesce operator cannot be applied to non-nullable value types. If you would like to make this work, you should make SelectedBackColor and SelectedForeColor in your _colors class nullable:

public Color? SelectedBackColor {get;set;}
public Color? SelectedForeColor {get;set;}

Now coalesce operator ?? works as expected. Moreover, the compiler has enough information to determine that _colors.SelectedForeColor ?? base.BackColor _colors.SelectedForeColor ?? base.BackColor never returns null , making the assignment to a property of non-nullable type legal.

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