Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# "Constant Objects" to use as default parameters

Tags:

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

like image 732
user623879 Avatar asked Mar 21 '11 00:03

user623879


2 Answers

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;     ... } 
like image 183
Ani Avatar answered Nov 03 '22 05:11

Ani


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.

like image 28
Jon Avatar answered Nov 03 '22 04:11

Jon