Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an optional parameter of type System.Drawing.Color

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.

like image 482
Neil N Avatar asked Aug 06 '10 02:08

Neil N


People also ask

What is the use of optional parameter?

What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.

How do you write an optional parameter?

Using Optional Attribute Here for the [Optional] attribute is used to specify the optional parameter. Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception.


1 Answers

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)

like image 167
Matthew Whited Avatar answered Oct 04 '22 01:10

Matthew Whited