C# “Constant Objects” to use as default parameters

心已入冬 提交于 2019-12-03 10:54:56

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) 
{ 
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!