16
votes

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

4 Answers

25
votes

Nullable value types can be used to help in situations like this.

public class MyObject 
{
    public Color Rgb { get; private set; }

    public MyObject(int foo, string bar, Color? rgb = null) 
    { 
        this.Rgb = rgb ?? Color.Transparent;
        // .... 
    } 
}

BTW, the reason this is required is because the default value is populated at the call point during compile and static readonly values are not set until runtime. (By the type initializer)

3
votes

I'm not a huge fan of optional parameters for cases like this at all. IMO the best use case for optional parameters is interop with COM, where optional parameters are used quite a bit. Situations like these are one of the reasons why (I would guess) that optional parameters didn't make it into the language until 4.0.

Instead of creating an optional parameter, overload the function like so:

public myObject(int foo, string bar) : this (foo, bar, Color.Transparent) {};

public myObject(int foo, string bar, Color RGB) {
...
}
1
votes

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

0
votes

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
    }

}