StringBuilder, add string if conditions are met

var sb = new StringBuilder ();

if (condition1) sb.Append ("one");
if (condition2) sb.Append ("two");
if (condition3) sb.Append ("three");
if (condition4) sb.Append ("four");
if (condition5) sb.Append ("five");

return sb.ToString ();

      

Any ideas how to improve it? How can I write less code while still producing the same result?

+3


source to share


4 answers


This code is fine. Keep it this way.

  • Every attempt to use extension methods or other methods will make this code less understandable and maintainable;
  • No duplicate code;
  • Until conditions affect others, there is no way to shorten if

    s.

If you need another option:



string s = 
   (condition1 ? "one" : null) + 
   (condition2 ? "two" : null) + 
   (condition3 ? "three" : null) + 
   (condition4 ? "four" : null) + 
   (condition5 ? "five" : null)
   ;

      

But honestly, does it make it any better? Not.

+9


source


You can do something like

var conditions = new[]
    {
        Tuple.Create(condition1, "one"),
        Tuple.Create(condition2, "two"),
        Tuple.Create(condition3, "three"),
        Tuple.Create(condition4, "four"),
        Tuple.Create(condition5, "five"),
    }

return string.Concat(conditions.Where(t => t.Item1).Select(t => t.Item2));

      



This is better? Not.

+2


source


I prefer the simple DSL definition approach, where it makes the code simpler or more readable. Also, pipeline expressions look amazing. In your case, it can be written like this:

var str =
    new StringBuilder()
        .AppendIf(condition1, "one")
        .AppendIf(condition2, "two")
        .AppendIf(condition3, "forty two")
        .ToString();

      

Using an extension method.

public static class StringBuilderExtensions
{
    public static StringBuilder AppendIf(
        this StringBuilder @this,
        bool condition,
        string str)
    {
        if (@this == null)
        {
            throw new ArgumentNullException("this");
        }

        if (condition)
        {
            @this.Append(str);
        }

        return @this;
    }
}

      

The approach is appropriate here if the conditions are repeated. For example arg1 != null

, arg2 != null

then you can use AppendIfNotNull

.

If not, think twice because it looks very similar to the initial implementation, requires additional code, can be slower due to additional null checks and method calls, and you must create an overload AppendIf

for each Append

.

+1


source


Another approach is to use string interpolation as described here https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated . Thus, the example can be modified as follows. I think it's easier to read.

var s = $"{(condition1 ? "one": null)}{(condition2 ? "two": null)}{(condition3 ? "three": null)}{(condition4 ? "four": null)}{(condition5 ? "five": null)}";

      

Edit: You can make the code easier to read by making it a verbatim string literal.

var s = $@"{
    (condition1 ? "one": null)
}{
    (condition2 ? "two": null)
}{
    (condition3 ? "three": null)
}{
    (condition4 ? "four": null)
}{
    (condition5 ? "five": null)}";

      

0


source







All Articles