ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

StringBuilder AppendIf

Makes it possible to conditionally append to a StringBuilder while keeping it fluent

Source

namespace Utils
{
    using System.Text;

    public static class Extensions
    {
        public static StringBuilder AppendIf(this StringBuilder builder, bool condition, string value)
        {
            if (condition) builder.Append(value);
            return builder;
        }
    }
}

Example

var keyBuilder = new StringBuilder();

keyBuilder.AppendIf(ctrl, "[ctrl]")
.AppendIf(shift, "[shift]")
.AppendIf(alt, "[alt]")
.Append(" ")
.Append(key);

Author: Lasse Sjørup

Submitted on: 9 apr. 2013

Language: C#

Type: System.Text.StringBuilder

Views: 7937