object
rather than a specific type CS-R1112Extension methods allow you to define methods for types of your choice. These methods are particularly useful if you do not wish to modify these types directly or to define derived types but rather "extend" their functionality. System.Linq
is a popular example where extension methods are defined to add further functionality to the already existing System.Collections.IEnumerable
and System.Collections.Generic.IEnumerable<T>
. However, it is recommended that you define such extension methods only for the types that you require in order to avoid introducing unnecessary complexities and confusion.
// Extension method defined for all types.
public static int ExtensionMethod(this object o)
{
}
// Extension method defined only for `System.String`.
public static int ExtensionMethod(this string s)
{
}