Using an optional parameter of type System.Drawing.Color

Viewed 6782

I am starting to take advantage of optional parameters in .Net 4.0

The problem I am having is when I try to declare an optional parameter of System.Drawing.Color:

public myObject(int foo, string bar, Color rgb = Color.Transparent)
{
    // ....
}

I want Color.Transparent to be the default value for the rgb param. The problem is, I keep getting this compile error:

Default parameter value for 'rgb' must be a compile-time constant

It really kills my plan if I can only use primitive types for optional params.

4 Answers

Updated using the 'default' keyword, available as of C# 7.1:

public myObject(int foo, string bar, Color rgb = default) {
    // ....
}

The default value of a Color struct is an empty struct, equivalent to Color.Transparent

Try this:

public myObject(int foo, string bar, string colorName = "Transparent")
{
    using (Pen pen = new Pen(Color.FromName(colorName))) //right here you need your color
    {
       ///enter code here
    }

}
Related