Extension methods for chaining
suggest changeWhen an extension method returns a value that has the same type as its this
argument, it can be used to “chain” one or more method calls with a compatible signature. This can be useful for sealed and/or primitive types, and allows the creation of so-called “fluent” APIs if the method names read like natural human language.
void Main()
{
int result = 5.Increment().Decrement().Increment();
// result is now 6
}
public static class IntExtensions
{
public static int Increment(this int number) {
return ++number;
}
public static int Decrement(this int number) {
return --number;
}
}
Or like this
void Main()
{
int[] ints = new[] { 1, 2, 3, 4, 5, 6};
int[] a = ints.WhereEven();
//a is { 2, 4, 6 };
int[] b = ints.WhereEven().WhereGreaterThan(2);
//b is { 4, 6 };
}
public static class IntArrayExtensions
{
public static int[] WhereEven(this int[] array)
{
//Enumerable.* extension methods use a fluent approach
return array.Where(i => (i%2) == 0).ToArray();
}
public static int[] WhereGreaterThan(this int[] array, int value)
{
return array.Where(i => i > value).ToArray();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents