6

I've taken on a Visual Studio C# project where my previous colleague used a lot of Extension Methods in static classes over multiple files depending on the uses.

In my previous experience I would be more selective when using Extension methods but instead use a public static method in a static class.

It got me thinking if one is better than the other or does it really just come down to flavor or an industry standard that I am unaware of?

Thanks,

4
  • 5
    See also: When do you use extension methods
    – Doc Brown
    Dec 19, 2018 at 17:44
  • 2
    Can you explain what you mean by more selective? An extension method is "a public static method in a static class" and can still be used as such. It just has the additional syntactic sugar of being callable with a different syntax.
    – nvoigt
    Dec 19, 2018 at 19:05
  • I actually do not have answer myself to why I would be more "selective". Perhaps an extension file already existed or a Static class I could sensibly place the new method existed instead. I'm scouring the opinions and expertise of others who can better put their thoughts an opinions down than I. Dec 19, 2018 at 19:20
  • 1
    "Better" is not a technical term and I usually tell engineers they should avoid using that word. Why not spend a moment and determine what you actually mean? If you do that you may find that the answer is much easier to come by.
    – John Wu
    Dec 26, 2018 at 23:58

4 Answers 4

12

I think extension methods are more "discoverable". If I have a certain type, Intelli-sense will automatically give me the extension methods.

When a static class and method, I have to know the name of the static class so I can reference it. In small projects, this may not make a difference, but this larger projects with several directories and many different files, an extension method may be easier to discover and use for someone new.

0
11

The biggest advantage for me is readability.

Consider for a moment a typical LINQ statement that uses method chaining:

var total = myList.Where(x => x.num > 5)
                  .Select(x => x.num)
                  .Distinct()
                  .Aggregate((total, next) => total + next);

Pretty easy to read. But you could use the static methods to do the same thing.

var total = Enumerable.Aggregate(Enumerable.Distinct(Enumerable.Select(Enumerable.Where(myList, x => x.num > 5), x.num)), (total, next) => total + next);

And even if I format it a little:

var total = Enumerable.Aggregate(
                Enumerable.Distinct(
                    Enumerable.Select(
                        Enumerable.Where(myList, x => x.num > 5)
                       , x.num)
                    )
               , (total, next) => total + next);

It still is hard to read. The lamdas are very far from the function names they go with. It becomes pretty hard to untangle that and understand what is really going on. The method chaining version is far easier to read (at least for me).

Pick what makes the code easiest to read and use. If an operation could be applicable to an object in most or any context, I'd go with an extension method (transformations, formatting, etc.) If it is only applicable in a certain context go with static methods (InterestCalculator.CalculateInterest(decimal principle, decimal interestRatePerMonth, int numberOfMonths) would make a poor extension method for either decimals or integers).

1
  • this should be marked as answer
    – Luke
    Dec 8, 2021 at 8:31
9

There is no industry standard here about whether to use extension methods or static classes. Honestly, "extension methods" are in static classes. This is a case where the language designers of C# allow us to have our cake, and eat it to.

Say you've got a traditional "utils" static class:

public static class AppUtils
{
    public static string ToStandardDateFormat(DateTime date)
    {
        // ... logic to format dates application-wide
    }
}

It's not so bad. You see @AppUtils.ToStandardDateFormat(someDate) in a bunch of razor templates. Pretty standard fare in applications across most tech stacks. With an additional 5 characters of code, you can do both:

public static class AppUtils
{
    public static string ToStandardDateFormat(this DateTime date)
    {
        // ... logic to format dates application-wide
    }
}

Now you can do either:

@AppUtils.ToStandardDateFormat(someDate)
@someDate.ToStandardDateFormat()

There is no guideline. No standard. Flip a coin in many cases. Heads or tails, then get back to coding.

6

The big gain for extension methods is that they allow you to add extra functionality to .Net Framework or 3rd party classes that you don't have the source code for or can't otherwise modify.

For example

public static class MyStringExtender
{
    /// <summary>
    /// Convert a string to a byte array using Ascii encoding
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static byte[] AsciiToByteArray(this string source)
    {
        return string.IsNullOrEmpty(source)
                   ? new byte[0]
                   : new ASCIIEncoding().GetBytes(source);
    }
}
1
  • 2
    +1 Indeed, and this is the exact reason why extension methods were implemented in the first place, if I remember correctly.
    – Andy Hames
    Jan 3, 2019 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.