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
CollectionExtensions
|
public static class CollectionExtensions
{
public static void AddEach<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if (elements == null)
{
throw new ArgumentNullException(nameof(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)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if (elements == null)
{
throw new ArgumentNullException(nameof(elements));
}
foreach (var element in elements)
{
collection.Remove(element);
}
}
public static void Remove<T>(this ICollection<T> collection, Func<T, bool> predicate)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
collection.RemoveEach(collection.Where(predicate));
}
public static void RemoveSingle<T>(this ICollection<T> collection, Func<T, bool> predicate)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
collection.Remove(collection.Single(predicate));
}
}
|