-
Notifications
You must be signed in to change notification settings - Fork 1
Extension Method Examples
Chris Dahlberg edited this page Mar 19, 2019
·
1 revision
The EnumerableExtensions
class provides extension methods for working with IEnumerable<T>
sequences. Most are inverted counterparts to existing extension methods that allow shorthand to be used for the filter function being passed in (for example, stringValues.Where(string.IsNullOrEmpty)
instead of stringValues.Where(x => string.IsNullOrEmpty(x))
).
string[] values = { "", null, "testing" };
bool areAnyNotNullOrEmpty = values.AnyNot(x => string.IsNullOrEmpty(x));
bool areAllNotNullOrEmpty = values.None(x => string.IsNullOrEmpty(x));
var nonNullOrEmptyValues = values.WhereNot(x => string.IsNullOrEmpty(x));
var valuesStartingAtNull = values.SkipUntil(x => x == null);
var valuesUntilFirstNull = values.TakeUntil(x => x == null);
The StringExtensions
class provides extension methods for working with string
objects.
// A Contains method that accepts a StringComparison parameter
bool containsCodeTiger = "An example for CodeTiger".Contains("codetiger", StringComparison.OrdinalIgnoreCase);
// A SplitAt method that splits a string at a specific location
string[] stringParts = "Testing".SplitAt(4);
The TypeExtensions
and TypeInfoExtensions
classes provide extension methods for working with Type
and TypeInfo
objects.
// An IsCompilerGenerated method determines whether a type was generated by the compiler
bool isCompilerGenerated = typeof(string).IsCompilerGenerated();
isCompilerGenerated = typeof(string).GetTypeInfo().IsCompilerGenerated();
// An IsStatic method determines whether a type is static
bool isStatic = typeof(string).IsStatic();
isStatic = typeof(string).GetTypeInfo().IsStatic();