2

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?

2
  • Can you use null as the default value and switch to Environment.NewLine inside the method when the argument is null? Commented Dec 18, 2018 at 20:56
  • 2
    You can always do it "the old way": write 2 methods; one with the delimiter and one without. Commented Dec 18, 2018 at 20:58

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

Paired with some good XML documentation to help with intellisense, this might work i.e. /// <param name="delimiter">Default value is really Environment.NewLine</param>. The comment would break down if the default were configurable however, but that's past the scope of my question anyway. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.