The difference between extension methods and methods in C #

What is the difference between Extension Methods and Methods in C #?

+4
source share
3 answers

I think you are really looking for the difference between Static and Instance Methods

At the end of the day, extension methods are nice compiler magic and syntactic sugar that allow you to call the Static method as if it were the method defined for that particular instance of the class. However, this is NOT an instance method, since an instance of this particular class must be passed to the function.

+7
source

ExtensionMethods: Allows you to define a set of methods for a class without subclassing another advantage over inheritance.

Methods: they are used to implement the operation for the class.

See an example of extension methods

+4
source

One very nice feature of extension methods is that they can be called on null objects, see this:

 myclass x = null; x.extension_method(); // this will work x.method(); // this won't 

It’s a pity that, for example, most string methods are not extension methods, because

 x.ToLower(); 

should return null if x is null. I mean that would be helpful.

When I need such transparency, I prefer to write extension methods.

+3
source

All Articles