Reputation: 15774
I prefer Environment.NewLine
over "\r\n"
whenever possible, even though this project is Windows-only. I was wondering if there was a way to use it as a default value of an optional parameter.
Consider the extension method
public static string ToSummaryString<T>(
this IEnumerable<T> items,
string delimiter = Environment.NewLine)
and the compile time error
Default parameter value for 'delimiter' must be a compile-time constant
I tried using parameter attributes too, with a similar fate
public static string ToSummaryString<T>(
this IEnumerable<T> items,
[Optional, DefaultParameterValue(Environment.NewLine)] string delimiter)
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
So is there any workaround? Or are my only options to hard-code it to "\r\n"
, or make it required?
Upvotes: 2
Views: 441
Reputation: 39966
You can replace your default value with Null
and then use null-coalescing operator, inside your method. Something like this:
public static string ToSummaryString<T>(this IEnumerable<T> items, string delimiter = null)
{
var realDelimiter = delimiter ?? Environment.NewLine;
}
As an alternative, you can also use Method-Overloading, as @Dennis_E also mentioned: write 2 methods; one with the delimiter and one without.
Upvotes: 2
Reputation: 460
It seems to me the best way to do this would be to have the default value be null, then check for that value in the method. If the parameter is null, set the default value to "\r\n." Better yet, have that default value be in a resource file so that you can change it as needed without having to recompile the app. (Putting the value in a config file works as well, of course)
Upvotes: 0