I dont have much experience of using these 2 ways to extend a class or create extension methods against a class. By looking others work, I have a question here.
I saw people using a partial class to extend an entity class in a project. Meanwhile, in the same project, there is another folder containing a lot extension methods to the entity class.
Is it right to do so? I mean these 2 ways both work well. Could you give me some real idea of how to pick one or the other when I want extend a class?
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.
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.
For an application programmer, extension methods are an incredibly powerful and expressive tool. They enable convenience, extensibility, and an improved intellisence experience. However, many of the features that make extension methods so useful for library consumers can be problematic for class library authors.
Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.
Some of differences that will determine whether you want to use a Partial Class or an Extension Method are
Partial Class
Extension Method
Partial classes should be used in code generation scenarios.
Since the generated file might get overwritten at any time, one uses partial classes to write into the non-generated file.
Additionally, partials will only work if they are part of the same assembly - they cannot cross assembly boundaries.
If these are not your constraints, you can and should use extension methods - of course, after considering other possibilities such as inheritance and composition for suitability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With