C# "Constant Objects" to use as default parameters

user623879 picture user623879 · Mar 21, 2011 · Viewed 16.4k times · Source

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??

Answer

Ani picture Ani · Mar 21, 2011

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;
    ...
}