2
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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
DidIReallyWriteThat
  • 1,033
  • 1
  • 10
  • 39

2 Answers2

7

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

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • 8
    @CalvinSmith no: it isn't – Marc Gravell Sep 03 '14 at 13:13
  • 1
    @CalvinSmith It may be `default(Color)` (that is the value you get for properties and fields if you don't explicitly set a value) but it is not null. – Scott Chamberlain Sep 03 '14 at 13:14
  • @MarcGravell So if I get a null color, that makes me like, awesome? – DidIReallyWriteThat Sep 03 '14 at 13:17
  • @CalvinSmith yes, because `System.Drawing.Color` isn't a reference type in the first place. You can't *have* a "color reference", unless you mean `ref Color` or `Color*`, which is not the same meaning of the word. – Marc Gravell Sep 03 '14 at 13:17
  • is `_colors` null? You don't tell us what that is and if that was null you could easily get a NullRefrenceException (If that is the [real problem you are trying to solve](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)). – Scott Chamberlain Sep 03 '14 at 13:18
  • 2
    @CalvinSmith If, however, you actually have a `Color?` (aka `Nullable`), then it *still* isn't a "color reference" – Marc Gravell Sep 03 '14 at 13:18
5

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523