C# Extensions

Created : 7/11/2022

Question

I typically use extension methods very sparingly. When I do feel compelled to write an extension method, I sometimes want to overload the method. My question is, what are your thoughts on extension methods calling other extension methods? Bad practice? It feels wrong, but I can't really define why.

For example, the second CaselessIs method calls the first:

public static bool CaselessIs(this string s, string compareTo)
{
    return string.Compare(s, compareTo, true) == 0;
}

public static bool CaselessIs(this string s, IEnumerable<string> compareTo)
{
    foreach(string comparison in compareTo)
    {
        if (s.CaselessIs(comparison))
        {
            return true;
        }
    }

    return false;
}

Would it be more appropriate to not do this? The downside would be that it violates DRY.

public static bool CaselessIs(this string s, string compareTo)
{
    return string.Compare(s, compareTo, true) == 0;
}

public static bool CaselessIs(this string s, IEnumerable<string> compareTo)
{
    foreach(string comparison in compareTo)
    {
        if (string.Compare(s, comparison, true) == 0)
        {
            return true;
        }
    }

    return false;
}
Questioned by : core

Answer

I would have to say that DRY controls here. Personally, I see nothing wrong with an extension method calling another extension method, especially if that other extension is contained within the same assembly. All-in-all, the method calls are just translated by the compiler from:

extended.ExtensionMethod(foo);

to:

StaticType.ExtensionMethod(extended, foo);

I don't see any problem chaining two static methods together, so transitively, I don't see a problem with chaining two extension methods.

Answered by : Marcus Griep