Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods vs Static Utility Class [closed]

I'm looking for some pros and cons for using extension methods over static utility classes in a C# app.

For instance, a plus in the extension methods column is the convinience of calling by the class name rather than something like "StringUtils". But a con would be that it can blur the lines between what is in the framework and what isn't.

like image 259
AJM Avatar asked Jan 10 '11 11:01

AJM


People also ask

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

Can we use extension method in sealed class?

You can't prevent it - there's no keyword to put on your class to stop this feature. If you have a class - someone can write an extension method for it.

Can we define extension methods for class which itself is a static class?

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.

Can extension methods only extend static classes?

No. Extension methods require an instance of an object.


1 Answers

I would say that a pro is that it blurs the lines between what is in the framework and what isn't: you can use your own code as naturally as framework code, operating on framework types.

Extension methods shouldn't be used arbitrarily, of course - it's not like all static methods should become extension methods.

I try to think of it as whether the method is logically operating "on" its first parameter. Would it make sense as an instance method, if you were able to include it as an instance method?

A "con" which you may not be aware of: if the extended type later adds an instance method of the same name which is applicable with the same parameters, your calling code will transparently start calling that instance method next time you recompile. For example, Stream gained CopyTo in .NET 4... I'd previously written a CopyTo extension method, which then wouldn't be called. There's no warning that this is occurring, so you have to be on your guard.

One caveat: extension methods haven't been around for long enough for best practices to really become established. You should weigh up all opinions (even - or perhaps especially - my own ones) carefully.

like image 86
Jon Skeet Avatar answered Sep 28 '22 05:09

Jon Skeet