using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Demo: Extension Methods
// Note: This must be a console application
public static class StringBuilderExtensions
{
public static StringBuilder AppendFormattedLine(this StringBuilder @this, string format, params object[] args)
return
@this
.AppendFormat(format, args)
.AppendLine();
}
public static StringBuilder AppendSequence<T>(
this StringBuilder @this,
IEnumerable<T> seq,
Func<StringBuilder, T, StringBuilder> fn)
// Aggregate is LINQ's name for what most functional languages call "Reduce"
// Iterate over each item in the sequence, applying the supplied function to each item and returning the StringBuilder
return seq.Aggregate(@this, fn);
public class Program
public static void Main()
var numbers = new [] { 1, 2, 3 };
var str =
new StringBuilder()
.AppendFormattedLine("Hello, {0}!", "Dave");
StringBuilderExtensions.AppendSequence(str, numbers,(sb,i) => sb.AppendFormattedLine(("\tItem {0}"), i));
//.AppendSequence(
// numbers,
// (sb, i) => sb.AppendFormattedLine("\tItem {0}", i))
//.ToString();
Console.WriteLine(str);