开发者

C# "Constant Objects" to use as default parameters

Is there any way to create a constant object(ie it cannot be edited and is created at compile time)?

I am just playing with the C# language and noticed the optional parameter feature and thought it might be neat to be able to use a default object as an optional parameter. Consider the following:

//this class has default settings
private const SettingsClass DefaultSettings = new SettingsClass ();

public void doSomething(SettingsClass settings = DefaultSettings)
{

}

This obviously does not compile, but is an example of what 开发者_运维问答I would like to do. Would it be possible to create a constant object like this and use it as the default for an optional parameter??


No, default values for optional parameters are required to be compile-time constants.

In your case, a workaround would be:

public void doSomething(SettingsClass settings = null)
{
    settings = settings ?? DefaultSettings;
    ...
}


Generally what you want is not possible. You can fake it with an "invalid" default value as Ani's answer shows, but this breaks down if there is no value you can consider invalid. This won't be a problem with value types where you can change the parameter to a nullable type, but then you will incur boxing and may also "dilute" the interface of the function just to accommodate an implementation detail.

You can achieve the desired functionality if you replace the optional parameter with the pre-C# 4 paradigm of multiple overloads:

public void doSomething()
{
    var settings = // get your settings here any way you like
    this.doSomething(settings);
}

public void doSomething(SettingsClass settings)
{
    // implementation
}

This works even if the parameter is a value type.


You could use the readonly attribute, instead of const. For example:

//this class has default settings 
private readonly SettingsClass DefaultSettings = new SettingsClass (); 

public void doSomething(SettingsClass settings = DefaultSettings) 
{ 
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜