IntroductionRight, now that we’re familiar with fluent interfaces it’s time to move to “Method Chaining”.
Extension Methods
In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.Using the StringBuilder class is simple:
[From MSDN]
var sb = new StringBuilder(); sb.Append("This is a simple list"); sb.AppendLine(); sb.Append("1. First item: "); sb.Append(items[0]); sb.AppendLine(); sb.Append("2. Second item: "); sb.Append(items[1]);The code above can also be written like this:
var sb = new StringBuilder() .Append("This is a simple list") .AppendLine() .Append("1. First item: ").Append(items[0]) .AppendLine() .Append("2. Second item: ").Append(items[1]);It’s up to you to decide which is more readable (#2) the fact is that writing the 2nd example is takes less time (try it), just keep using “.” after each method call.
[SecuritySafeCritical] public unsafe StringBuilder Append(string value) { if (value != null) { // Here be code! } return this; }This means that we can invoke more methods on the same class one after the other.
Labels: .NET, C#, DSL, Tips and Tricks