views:

179

answers:

0

Duplicate:

Post your extension goodies for C# .Net (codeplex.com/extensionoverflow)


Let's create a list of your favorite extension methods. To qualify it should be an extension method you use often and makes coding easier by being either elegant, clever, powerful or just very cool.

I'll start with my 3 favorite extension methods that I find elegant and use all the time (I left out the code checking if arguments are valid to keep it short):

1: String.FormatWith(...)

public static string FormatWith(this string text, params object[] values) {
    return String.Format(text, values);
}

So instead of having to write

String.Format("Some text with placeholders: {0}, {1}", "Item 1", "Item 2");

you can write

"Some text with placeholders: {0}, {1}".FormatWith("Item 1", "Item 2");

2: Object.To()

public static T To<T>(this object obj) {
    return (T) obj;
}

So instead of having to write

object o = 5; //integer as object
string value = ((int)o).ToString(); //get integer value as string
int number = (int) o;

you can write

object o = 5; //integer as object
string value = o.To<int>().ToString();
int number = o.To<int>();

3: IEnumerable.Apply(Action action)

public static void Apply<T>(this IEnumerable<T> enumerable, Action<T> action) {
    foreach (T item in enumerable) action(item);
}

So instead of having to write

private void PrintNumbers(int number) { Debug.WriteLine(number); }

int[] numbers = new []{ 1, 2, 3, 4, 5};
foreach (int number in numbers)
   WriteLine(number);

You can write

private void PrintNumbers(int number) { Debug.WriteLine(number); }

int[] numbers = new int[] { 1, 2, 3, 4, 5};
numbers.Apply(PrintNumbers)