How to do this without unchecked?
Question
a few months ago I wrote this code because it was the only way I could think to do it(while learning C#), well. How would you do it? Is unchecked
the proper way of doing this?
unchecked //FromArgb takes a 32 bit value, though says it's signed. Which colors shouldn't be.
{
_EditControl.BackColor = System.Drawing.Color.FromArgb((int)0xFFCCCCCC);
}
Solution
You could break down the components of the int and use the FromArgb()
overload that takes them separately:
System.Drawing.Color.FromArgb( 0xFF, 0xCC, 0xCC, 0xCC);
OTHER TIPS
It takes a signed int b/c this dates back to the time when VB.NET didn't have unsigned values. So in order to maintain compatibility between C# and VB.NET, all the BCL libraries utilize signed values, even if it does not make logical sense.
Extension methods can hide this:
public static Color ToColor(this uint argb)
{
return Color.FromArgb(unchecked((int)argb));
}
public static Color ToColor(this int argb)
{
return Color.FromArgb(argb);
}
Usage:
0xff112233.ToColor();
0x7f112233.ToColor();
Seems like they're should be another notation (like 0v12345678) or some other way to work around this issue.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow