I was just curious what a best practices solution would be given my current situation. I have a database storing colors in ARGB integer form, but I allow it to be nullable since sometimes the color may not need to be specified. Using the Entity Framework, I have a generated class with a ColorArgb property for accessing that column that returns and int, as expected. I've also manually added another property, Color, that returns a System.Drawing.Color object. The Color property is pretty much just a go between so I can interact with the generated class in a more natural fashion. Setting is as simple as:
ColorArgb = value.ToArgb();
However, getting is a little more interesting. Here's what I have so far:
return ColorArgb == null ? Color.Empty : Color.FromArgb(ColorArgb ?? 0);
As you can see, I want to maintain the idea that a Color is not necessary for this class, so I return Color.Empty when the underlying ARGB value is null, but the right hand side of the null coalescing operator is never reached. I have guaranteed that the value is not null, but I don't know how to explicitly tell the compiler in a best practices form. Not a serious issue, but I would like to learn. As such, all help is greatly appreciated.
Edit: ColorArgb is of type System.Nullable<int>
You don't have to use the null coalescing operator if you know that the value is not null. Instead use ColorArgb.Value
:
return ColorArgb == null ? Color.Empty : Color.FromArgb(ColorArgb.Value);