What are your favorite extension methods?

Duplicate:

Post your add-ons for C # .Net (codeplex.com/extensionoverflow)


Create a list of your favorite extension methods. To qualify, it must be an extension method that you often use, and simplifies coding, be it elegant, smart, powerful, or just very cool.

I will start with my 3 favorite extension methods, which I find elegant and use all the time (I left the verification code if the arguments are correct to keep it short):

1: String.FormatWith (...)

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

Therefore, instead of writing

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;
}

Therefore, instead of writing

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)

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

Therefore, instead of writing

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)
+5
source share

All Articles