What are the benefits of extension methods you find?

An unbeliever from C # asked me what the purpose of extension methods was. I explained that you could add new methods to objects that have already been defined, especially if you do not own / control the source of the original object.

He raised "Why not just add a method to your class?" We walked around (in a good way). My general answer is that this is another tool in the toolbox, and its answer is a waste of the tool ... but I thought I would get a more "enlightened" answer.

What are some of the scenarios that you used extension methods that you couldn't (or shouldn't) use a method added to your own class?

+82
c # extension-methods
Jan 28 '09 at 14:55
source share
30 answers

I think extension methods help when writing code, if you add extension methods to the base types, you will quickly get them in intellisense.

I have a file format format provider. To use it, I need to write:

Console.WriteLine(String.Format(new FileSizeFormatProvider(), "{0:fs}", fileSize)); 

Creating an extension method that I can write:

 Console.WriteLine(fileSize.ToFileSize()); 

More clean and simple.

+31
Jan 28 '09 at 15:07
source share

The only advantage of extension methods is code readability. What is it.

Extension methods allow you to do this:

 foo.bar(); 

instead of this:

 Util.bar(foo); 

Now in C # there are many things that look like this. In other words, there are many functions in C # that seem trivial and not very useful in their own right. However, as soon as you start combining these functions together, you will begin to see something just a little more than the sum of its parts. LINQ greatly benefits from extension methods, since LINQ queries will be almost unreadable without them. LINQ will be possible without extension methods, but not practical.

Extension methods are very similar to partial C # classes. By themselves, they are not very useful and seem trivial. But when you start working with a class that needs the generated code, partial classes begin to make more sense.

+80
Jan 28 '09 at 15:04
source share

Do not forget to equip! When you add an M extension method of type Foo, you get "M" in the Foo intellisense list (assuming the extension class is in scope). This makes "M" a lot easier than MyClass.M (Foo, ...).

In the end, it's just syntactic sugar in other places - static methods, but like buying a house: "location, location, location!" If he hangs on a type, people will find him!

+32
Jan 28 '09 at 15:01
source share

Two other advantages of the extension methods I came across:

  • a free interface can be encapsulated in a static class of extension methods, thereby achieving separation of problems between the main class and its current extensions; I saw that they achieve greater maintainability
  • extension methods can be disconnected from interfaces, which allows you to specify the contract (via the interface) and the associated sequence of actions based on the interface (via extension methods), again suggesting separation of problems.
+28
Jan 28 '09 at 15:18
source share

Some of the best uses I've used for extension methods are the opportunity:

  • To expand the functionality of third-party objects (whether commercial or internal for my company, but managed by a separate group), which in many cases will be marked as sealed .
  • Create default functionality for interfaces without the need for an abstract class

Take, for example, IEnumerable<T> . Although it is rich in extension methods, I was annoyed that it did not implement the general ForEach method. So, I made my own:

 public void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) { foreach ( var o in enumerable ) { action(o); } } 

Voila, all my IEnumerable<T> objects, regardless of the type of implementation, and whether I wrote this or someone else, now has a ForEach method, adding the appropriate "using" to my code.

+26
Jan 28 '09 at 15:52
source share

One of the main reasons for using extension methods is LINQ. Without extension methods, much of what you can do in LINQ would be very difficult. The Where (), Contains (), Select extension methods mean that much more functionality is added to existing types without changing their structure.

+12
Jan 28 '09 at 15:01
source share

There are many answers about the benefits of extension methods; how about addressing flaws ?

The biggest drawback is the lack of a compiler error or warning if you have a regular and extension method with the same signature in the same context.

Suppose you have created an extension method that applies to a specific class. Then later, someone creates a method with the same signature on this same class.

Your code will compile and you won’t even be able to get a runtime error. But you are no longer using the same code as before.

+9
Jan 21
source share

Free interfaces and contextual sensitivity demonstrated by Greg Young on CodeBetter

+8
Jan 28 '09 at 15:05
source share

My personal argument regarding extension methods is that they fit well with OOP design: consider a simple method

 bool empty = String.IsNullOrEmpty (myString) 

compared with

 bool empty = myString.IsNullOrEmpty (); 
+4
Jan 28 '09 at 15:04
source share

There are tons of great answers above about what extension methods let you do.

My short answer is that they almost eliminate the need for plants.

I will simply point out that they are not a new concept, and one of their most important statements is that they are a killer function in Objective-C (categories). They add so much flexibility for framework development that NeXT used NSA and Wall Street financial modelers as their primary users.

REALbasic also implements them as extension methods, and they were of similar use, simplifying development.

+4
Feb 05 '09 at 5:15
source share

I would like to support other answers here that mention improved code readability as an important reason underlying extension methods. I will demonstrate this with two aspects of this: chaining methods against nested method calls and cluttering a LINQ query with meaningless static class names.




As an example, take this LINQ query:

 numbers.Where(x => x > 0).Select(x => -x) 

Both Where and Select are extension methods defined in the static Enumerable class. Thus, if the extension methods did not exist, and these were ordinary static methods, the last line of code should look something like this:

 Enumerable.Select(Enumerable.Where(numbers, x => x > 0), x => -x) 

See how much more annoying this request is.




Secondly, if you want to present your own query operator, you naturally cannot define it inside the static Enumerable class, like all other standard query operators, since Enumerable is in the structure and you do not have control over this class. Therefore, you will need to define your own static class containing extension methods. Then you can get requests like this:

 Enumerable.Select(MyEnumerableExtensions.RemoveNegativeNumbers(numbers), x => -x) // ^^^^^^^^^^^^^^^^^^^^^^ // different class name that has zero informational value // and, as with 'Enumerable.xxxxxx', only obstructs the // query actual meaning. 
+4
Sep 15 '10 at 19:21
source share

It is true that you can add your extension method directly to your class. But not all classes are written by you. Classes from the main library or third-party libraries are often closed, and it is impossible to get syntactic sugar without extension methods. But remember that extension methods are similar to (static) stand-alone methods, for example. C ++

+3
Jan 28 '09 at 15:07
source share

Extension methods can also help clear your classes and class dependencies. For example, you might need the Bar () method for the Foo class, where Foo is used. However, you may need the .ToXml () method in another assembly and only for this assembly. In this case, you can add the necessary System.Xml and / or System.Xml.Linq dependencies in this assembly, and not in the original assembly.

Advantages: Dependencies in your assembly of the defined class are reduced only to basic needs, while other consuming nodes will be prohibited from using the ToXml () method. See this PDC presentation for details.

+3
Jan 28 '09 at 17:02
source share

Extension methods are really .NET integration ā€œImplement a foreign methodā€ to the refactor from Martin Fowler’s book (up to the signature of the method). They come mainly with the same advantages and traps. In the section on this refactor, he says that they work when you cannot modify the class that this method should really have.

+2
Jan 28 '09 at 15:08
source share

Basically, I see extension methods as an assumption that maybe they shouldn't have forbidden free features.

In the C ++ community, it is often considered good OOP practice that prefers free memberless functions over members because these functions do not break encapsulation, gaining access to those private members that they do not need. Extension methods seem to be a workaround to achieve the same. That is, a cleaner syntax for static functions that do not have access to private members.

Extension methods are nothing more than syntactic sugar, but I see no harm in using them.

+2
Jan 28 '09 at 15:34
source share
  • Intellisense for the object itself, not for calling some ugly utility function
  • For the conversion functions, you can change "XToY (X x)" to "ToY (this X x)", which leads to content x.ToY () instead of the ugly XToY (x).
  • Extend classes in which you do not control
  • Extend the functionality of classes when it is undesirable to add methods to the classes themselves. For example, you can keep business objects simple and logic-free and add specific business logic with ugly dependencies in extension methods.
+2
Feb 01 '09 at 4:45
source share

I use them to reuse object model classes. I have a group of classes that represent the objects that I have in the database. These classes are used on the client side only to display objects, so the main use is access to properties.

 public class Stock { public Code { get; private set; } public Name { get; private set; } } 

Because of this usage pattern, I don’t want to have business logic methods in these classes, so I make every business logic as an extension method.

 public static class StockExtender { public static List <Quote> GetQuotesByDate(this Stock s, DateTime date) {...} } 

Thus, I can use the same classes to process business logic and display the user interface without overloading the client side with unnecessary code.

Interestingly, my object model classes are dynamically generated using Mono.Cecil , so it would be very difficult to add business logic methods even if I wanted to. I have a compiler that reads XML definition files and generates these stub classes representing some object that I have in the database. The only approach in this case is to expand them.

+2
Feb 05 '09 at 4:19
source share

I agree that extension methods increase code readability, but that’s really nothing but static helper methods.

IMO using extension methods to add behavior to your classes could be:

Mixing: Programmers may think that methods are part of an extended type, so they don’t understand why methods disappeared when the extension namespace is not imported.

Antipattern: You decided to add behavior to types in your structure using extension methods, and then send them to someone who is in unit testing. Now he is stuck with a framework containing many methods that he cannot fake.

+2
Sep 15 '10 at 18:21
source share

This allows C # to better support dynamic languages, LINQ, and a dozen other things. Check out Scott Guthrie's article .

+1
Jan 28 '09 at 15:06
source share

In my last project, I used an extension method to attach Validate () methods to business objects. I justified this because business objects where serializable data transfer objects will be used in different domains, like them, where are common e-commerce objects such as product, customer, seller, etc. Business rules can be different in different domains, so I encapsulated my late related validation logic in the Validate method, which is included in the base class of data transfer objects. Hope this makes sense :)

+1
Jan 28 '09 at 15:26
source share

One case where extension methods were quite useful was in a client application using ASMX web services. Because of serialization, the returned types of web methods do not contain any methods (only public properties of these types are available on the client).

Extension methods allow you to use functionality (on the client side) for types returned by web methods, without the need to create another object model or numerous wrapper classes on the client side.

+1
Jan 29 '09 at 0:15
source share

Also remember that extension methods have been added as a way to help the Linq query be more readable when used in their C # style.

These 2 affectations are absolutely equivalent, but the first one is much more readable (and the gap in readability, of course, will widen with more methods).

 int n1 = new List<int> {1,2,3}.Where(i => i % 2 != 0).Last(); int n2 = Enumerable.Last(Enumerable.Where(new List<int> {1,2,3}, i => i % 2 != 0)); 

Note that the full syntax should be:

 int n1 = new List<int> {1,2,3}.Where<int>(i => i % 2 != 0).Last<int>(); int n2 = Enumerable.Last<int>(Enumerable.Where<int>(new List<int> {1,2,3}, i => i % 2 != 0)); 

Incidentally, parameters like Where and Last should not be explicitly specified, since they can be inferred due to the presence of the first parameter of these two methods (the parameter that is entered with the this and make them extension methods).

This point is obviously an advantage (among others) of extension methods, and you can take advantage of it in every such scenario in which a chain of methods is involved.

In particular, this is a more elegant and convincing way that I found a base class method called by any subclass and returning a strongly typed reference to this subclass (with the type of the subclass).

Example (well, this scenario is completely trashy): after a good night, the animal opens its eyes and then screams; each animal opens its eyes in the same way, while the dog barks and ducks.

 public abstract class Animal { //some code common to all animals } public static class AnimalExtension { public static TAnimal OpenTheEyes<TAnimal>(this TAnimal animal) where TAnimal : Animal { //Some code to flutter one eyelashes and then open wide return animal; //returning a self reference to allow method chaining } } public class Dog : Animal { public void Bark() { /* ... */ } } public class Duck : Animal { public void Kwak() { /* ... */ } } class Program { static void Main(string[] args) { Dog Goofy = new Dog(); Duck Donald = new Duck(); Goofy.OpenTheEyes().Bark(); //*1 Donald.OpenTheEyes().Kwak(); //*2 } } 

Conceptually, OpenTheEyes should be an Animal method, but then it should return an instance of the Abstract class Animal , which does not know the specific methods of the subclass, such as Bark or Duck or something else. 2 lines commented out as * 1 and * 2 will then raise a compilation error.

But thanks to extension methods, we can have a kind of "base method that knows the type of subclass on which it is called."

Note that a simple general method could do the job, but much more inconveniently:

 public abstract class Animal { //some code common to all animals public TAnimal OpenTheEyes<TAnimal>() where TAnimal : Animal { //Some code to flutter one eyelashes and then open wide return (TAnimal)this; //returning a self reference to allow method chaining } } 

This time, no parameters, and therefore impossible return type return. A call can be nothing more than:

 Goofy.OpenTheEyes<Dog>().Bark(); Donald.OpenTheEyes<Duck>().Kwak(); 

... which can weigh a lot if more chain is involved (especially knowing that the type parameter will always be <Dog> on the Goofy line and <Duck> on the Donald one ...)

+1
Jan 15 2018-11-21T00:
source share

I have only one word to say about this: IMPROVEMENT is the key to using extension methods

0
Jan 28 '09 at 14:58
source share

I think extension methods help write more understandable code.

Instead of introducing a new method inside your class, as suggested by your friend, you put it in the ExtensionMethods namespace. In this way, you maintain a logical sense of order for your class. Methods that really aren’t directly related to your class will not clutter it.

I feel that extension methods make your code clearer and more organized.

0
Jan 28 '09 at 16:23
source share

This allows your editor / IDE to make auto-complete sentences smart.

0
Feb 05 '09 at 5:43
source share

I love them for creating html. Often there are sections that are reused or recursively generated when the function is useful, but otherwise disrupts the program flow.

  HTML_Out.Append("<ul>"); foreach (var i in items) if (i.Description != "") { HTML_Out.Append("<li>") .AppendAnchor(new string[]{ urlRoot, i.Description_Norm }, i.Description) .Append("<div>") .AppendImage(iconDir, i.Icon, i.Description) .Append(i.Categories.ToHTML(i.Description_Norm, urlRoot)).Append("</div></li>"); } return HTML_Out.Append("</ul>").ToString(); 

There are also situations where an object needs special logic, which must be prepared for HTML methods for expanding output, allowing you to add this functionality without mixing presentation and logic inside the class.

0
Sep 19 '09 at 21:28
source share

I found extension methods useful for matching nested general arguments.

This sounds a little strange - but let's say that we have a common class MyGenericClass<TList> , and we know that TList itself is common (like List<T> ), I don’t think there is a way to dig this nested 'T' from a list without extension methods or static helper methods. , () () , , .

eg. :

 public class Tuple { } public class Tuple<T0> : Tuple { } public class Tuple<T0, T1> : Tuple<T0> { } public class Caller<TTuple> where TTuple : Tuple { /* ... */ } public static class CallerExtensions { public static void Call<T0>(this Caller<Tuple<T0>> caller, T0 p0) { /* ... */ } public static void Call<T0, T1>(this Caller<Tuple<T0, T1>> caller, T0 p0, T1 p1) { /* ... */ } } new Caller<Tuple<int>>().Call(10); new Caller<Tuple<string, int>>().Call("Hello", 10); 

, , - , ? Any thoughts?

0
21 . '10 21:29
source share

mixin #.

, , . .

#, , DCI .

0
15 . '10 18:25
source share

, ( , ..). , (TextInputBox ..).

, , , , WebControl, WebControl , .

:

1) WebControl,

2), , , , IInputZone, . , , . , , .

0
04 . '10 12:23
source share

, IEnumerables, .

eg. IEnumerable<myObject> , IEnumerable<myObject>

 mylist List<myObject>; 

...

 mylist.DisplayInMyWay(); 

:

 myDisplayMethod(myOldArray); // can create more nexted brackets. 

- !

""!

, .

 myNode.NextOrFirst().DisplayInMyWay(); 

but not

 DisplayInMyWay(NextOrFirst(myNode)). 

. . :

 myNode.Next.DoSomething() 

!:)

0
28 . '12 9:27
source share



All Articles