Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of extension methods?

Extension method is a really helpful feature that you can add a lot of functions you want in any class. But I am wondering if there is any disadvantage that might bring troubles to me. Any comments or suggestions?

like image 478
Sonic Lee Avatar asked Nov 23 '08 05:11

Sonic Lee


People also ask

What is an advantage of using extension methods?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.

What are the important issues in group extension method?

Important issues in group extension First, he should try to develop the group, to encourage its members to continue to meet and to establish the group on a permanent basis. In this way, the agent will be developing a base from which group members can continue their development efforts.


2 Answers

  • The way that extension methods are imported (i.e. a whole namespace at a time) isn't granular. You can't import one extension from a namespace without getting all the rest.
  • It's not immediately obvious from the source code where the method is defined. This is also an advantage - it means you can make your code look consistent with the rest of the methods on the type, even if you can't put it in the same place for whatever reason. In other words, the code is simpler to understand at a high level, but more complicated in terms of exactly what's being executed. I'd argue this is true of LINQ in general, too.
  • You can only have extension methods, not properties, indexers, operators, constructors etc.
  • If you're extending a 3rd party class and in a later version they introduce a new method with the same signature, you won't easily know that the meaning of your calling code has changed. If the new method is very similar to your extension, but with subtly different boundary conditions (or whatever) then this could lead to some very tricky bugs. It's relatively unlikely to happen though.
like image 142
Jon Skeet Avatar answered Sep 23 '22 04:09

Jon Skeet


Couple of things:

  • It's not always clear as to where the extension method comes from unless you are inside VS.NET
  • Extension methods can't be resolved via reflection or C# 4.0's dynamic lookup
like image 41
Buu Nguyen Avatar answered Sep 23 '22 04:09

Buu Nguyen