Search code examples
c#null-coalescing-operatornull-coalescing

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


Solution

  • 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 never returns null, making the assignment to a property of non-nullable type legal.