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 idea how to improve it? How to write less code, giving same result?
append() method is used to append the string representation of some argument to the sequence.
Because it is passed by reference. The reference to the StringBuilder is passed by value. You can add characters and they will be in the instance after the method returns. Same way you can pass a Collection and add values inside the invoke method - these will be preserved.
append(int i) method appends the string representation of the int argument to this sequence.
append(String str) method appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument.
This code is fine. Keep it like this.
if
s.If you do want another option:
string s =
(condition1 ? "one" : null) +
(condition2 ? "two" : null) +
(condition3 ? "three" : null) +
(condition4 ? "four" : null) +
(condition5 ? "five" : null)
;
But let's be honest, does this make it better? No.
I prefer approach with simple DSLs definition, when it makes code simpler or more readable. Also "pipeline-style" expressions are awesome. In your case it can be written like this:
var str =
new StringBuilder()
.AppendIf(condition1, "one")
.AppendIf(condition2, "two")
.AppendIf(condition3, "forty two")
.ToString();
With 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;
}
}
Approach is suitable here, if conditions are repeated. For example arg1 != null
, arg2 != null
, then AppendIfNotNull
can be used.
Otherwise, think twice, because it looks quite similar to initial implementation, requires additional code, can be slower because of additional null checks and method invocations, and also you should create an AppendIf
overload for every Append
one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With