Disponible à partir de C# 3, elles permettent d'ajouter des méthodes à une classe ou à une structure sans en modifier son code.
 |
- Les méthodes doivent être déclarées dans une classe static.
- Les méthodes qui étendent une classe ou une structure ne peuvent accéder qu’aux membres publics.
|
|
public static class StringExtensions
{
public static bool Contains(this string source, string value, StringComparison comparisonType)
{
return source.IndexOf(value, comparisonType) >= 0;
}
}
var monString = "ASTRINGTOTEST";
monString.Contains("string", StringComparison.OrdinalIgnoreCase);
|
Useful extension methods
CollectionExtension
CollectionExtension.cs
|
public static void AddEach<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
ArgumentNullException.ThrowIfNull(collection);
ArgumentNullException.ThrowIfNull(elements);
if (collection is List<T> list)
{
list.AddRange(elements);
}
else
{
foreach (var element in elements)
{
collection.Add(element);
}
}
}
public static void RemoveEach<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
ArgumentNullException.ThrowIfNull(collection);
ArgumentNullException.ThrowIfNull(elements);
foreach (var element in elements)
{
collection.Remove(element);
}
}
public static void Remove<T>(this ICollection<T> collection, Func<T, bool> predicate)
{
ArgumentNullException.ThrowIfNull(collection);
collection.RemoveEach(collection.Where(predicate));
}
public static void RemoveSingle<T>(this ICollection<T> collection, Func<T, bool> predicate)
{
ArgumentNullException.ThrowIfNull(collection);
collection.Remove(collection.Single(predicate));
}
|
IEnumerableExtension
IEnumerableExtension.cs
|
public static IEnumerable<T> SetValue<T>(this IEnumerable<T> items, Action<T> updateMethod)
{
foreach (T item in items)
{
updateMethod(item);
}
return items;
}
public static IEnumerable<T> OrderBy<T>(
this IEnumerable<T> source,
string propertyName,
bool ascendingOrder)
{
var propertyDescriptor = TypeDescriptor.GetProperties(typeof(T))
.Find(propertyName, false);
if (propertyDescriptor == null)
throw new Exception($"Property '{propertyName}' not found.");
return ascendingOrder ?
source.OrderBy(x => propertyDescriptor.GetValue(x)) :
source.OrderByDescending(x => propertyDescriptor.GetValue(x));
}
|