2

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,

  • 5
    See also: When do you use extension methods – Doc Brown Dec 19 '18 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 '18 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. – Bryan Harrington Dec 19 '18 at 19:20
  • "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 '18 at 23:58
8

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.

5

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.

4

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
    +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 at 9:38
3

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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