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

- 1,421,763
- 867
- 9,128
- 9,194
-
great explanation. Is extension methods harmful in such scenarios if calling by multiple users at same time. like I have one extension method `public static A ToDTO(this AD ad) { return AutoMapper.Mapper.Map(ad); }` and I am making call like this `AD.ToDTO()` - its working fine when using by single user, but its app stuck on this method when called by multiple users and after sometime throw timeout exception, is it kind of drawback of Extension methods, like we have a static class here. – Gaurav Arora Jun 26 '14 at 14:10
-
1@GauravKumarArora: The fact that something is an extension method is irrelevant to that - if it would be safe as a normal static method, called in the "old style" then it's safe as an extension method. Assuming by "multiple users" you're really talking about thread safety, extension methods neither provide nor remove any kind of thread safety. – Jon Skeet Jun 26 '14 at 14:26
-
1We can't mock the extension method during unit testing. – Sandeep Shekhawat Sep 09 '21 at 14:10
-
If granularity is ever an issue, that can be solved by not importing a namespace and then calling specific extension methods fully qualified. `MyNamespace.ExtMethod(myObject, params)` That forgoes the pretty syntax, but it's just a function. (Really the annoyance of importing an entire namespace can be an issue for any entity in the namespace, so that's not really unique to extension methods. Using aliases with #include can reduce the pain in some cases.) – C Perkins Mar 02 '23 at 23:00
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

- 49,745
- 5
- 67
- 85
-
1You can find extension-methods via reflection. Look for the attribute 'ExtensionAttribute'. Take a look at http://stackoverflow.com/questions/299515/c-reflection-to-identify-extension-methods – Patrik Svensson Nov 23 '08 at 12:58
-
@Patrik - but you can't do it unambiguously, since you don't know which "usings" should be considered. Sometimes it matters. – Marc Gravell Nov 23 '08 at 15:46
-
1@Patrik: What I meant about "resolution" was: while you can call myType.extendedMethod(), you can't do it via usual reflection code, i.e. typeof(MyType).GetMethod("extendedMethod").Invoke(...), or dynamic lookup, i.e. dynamic myType = new MyType(); myType.extendedMethod(); – Buu Nov 26 '08 at 15:02
The null-checking with static methods is different. Not necessarily better or worse - but different, and the developer needs to understand that. Being able to call a method on a null value can be unexpected, and can (at times) be very useful.
No polymorphism (although overloading is supported)
You can get into a mess with ambiguity if two extension methods conflict for the source type (and neither qualifies as "better"). The compiler then refuses to use either... which means adding an extension method in assembly A can break* unrelated code in assembly B. I've seen this a couple of times...
You can't use in with C# 2.0, so if you are writing a library for C# 2.0 it doesn't help
It needs [ExtensionAttribute] - so if you are writing a library for .NET 2.0 you get into a pickle: if you declare your own [ExtensionAttribute], it might conflict from a .NET 3.5 caller
Don't get me wrong though - I'm a big fan!
You can probably guess I'm currently writing a library that needs to work for C# 2.0 and .NET 2.0 callers - and where (annoyingly) extension methods would be really, really useful!
*=for the compiler only; code that is already compiled will be fine

- 1,026,079
- 266
- 2,566
- 2,900
-
Even though extension method calls cannot be dispatched polymorphically, extension methods can use various means to vary their action according to the types upon which they are invoked. For example, one could define a `SafeEquals
(this T it, U other)` extension method which would invoke a `Func – supercat Dec 06 '13 at 22:23` stored in `SafeComparer .CheckEquality(it, other)` [the default delegate would examine `T` and `U` and determine how to perform the comparison].
Extension methods are fun, but there are potential problems with them. For instance, what if you write an extension method and another library creates an extension method with the same signature? You will end up with difficulties in using both namespaces.
Also, it can be argued that they are less discoverable. I think it depends on this one. In some cases your code should be wrapped up in a class, in other cases it's fine to add that functionality as an extension method.
I generally make extension methods as wrappers to my own classes or BCL classes, and put them in a different name space. e.g. Utils and Utils.Extensions. That way the extesions don't have to be used.

- 25,684
- 22
- 96
- 122
-
1@ the duplicate signatures comment: Its an inherent risk in a lot of other languages too and people manage OK. Though it may still be a disadvantage, it's an unlikely one, in most cases, IMO. – Chris Nov 23 '08 at 06:25
Its hard for me to imagine to add a method without knowing intimately about an existing code. For example, you've been using a third-party class to do something, what would be the need for you to extend functionality of this class given that you're not the original developer and you have no ideas how things are structured in the class? It's almost pointless to do such a thing just like it's pointless to drive when you can't see. In the case LINQ where it's implemented by Microsoft designers/codes, it made a lot of sense since they possess the knowledge of how say an internal of implementation of a sequence and now they want to extend its functionality by adding the Count method to count all the elements in the sequence. By having said this, I wish someone would argue me wrong by giving a realistic example where extension method is needed.

- 59
- 4
-
A simple example would be, say, adding an "IsNullOrWhiteSpace()" extension method to strings. – jkerak Nov 14 '18 at 21:19
As far as disadvantages go, I would see them a bit like macros - you can potentially end up with code that is harder to maintain because others might not be familiar with the extensions you added.

- 131,367
- 29
- 160
- 239
There are two different scenarios where extension methods come into play:
- If you want to extend any class, struct of interface coming from an external assembly, except for the classes which are not marked as sealed where you may have an option to derive from those classes and extend them with additional methods, you have only and I repeat only this option available. Sealed classes and struct can not be inherited and point less to mention interfaces.
In your own assembly, however, providing an extension method to a particular class or struct or interface is a very design subjective matter. If you want to be generious to people who will use your assembly you may create very small interfaces ideally with few properties and then attach whole bunch of extension methods to them. Here is the example:
public interface IPointF{ float X { get; } float Y { get; } } public struct PointF: IPointF{ public PointF(float x, float y){ X=x;Y=y; } public float X { get; private set; } public float Y { get; private set; } } public static class PointHelper{ public static PointF ADD(this IPointF p, float val){ return new PointF(p.x+val, p.y+val); } }
So any future user can save lot of time in coding by inheriting IPoint.

- 642
- 5
- 16