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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With