I’ve got a C# method that takes a bunch of parameters, all of which have default values. One of the parameters is a List. I can’t figure out how to specify that the List should default to empty. Here’s what it looks like:
public static void execute(
String condition = "Unnamed condition",
List<String> messages,
Object actual = null,
Object expected = null)
I can’t quite figure out how to specify that messages should be empty by default. When I enter:
...
List<String> messages = new List<String> ()
...
it complains that “default parameter value for ‘messages’ must be a compile-time constant”.
Any ideas?
Because default parameter values must be compile-time expressions, the only acceptable default parameter value for reference types is
null.You can get around this with an overload, though:
Or constructing a list if the argument is
null. If you must need a list and want to treat allnullas an empty list, this would also handle if they called withnullexplicitly.Or, if messages is only used in one place, you can use the null-coallescing operator to substitute an empty enumeration:
Though obviously a simple if-guard can be more efficient. Really depends if you want to treat it as an empty enumerable or as an empty list or just bypass logic…