Thomas Anderson
Thomas Anderson

Reputation: 2067

Difference between Extension methods and Methods in C#

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

Upvotes: 4

Views: 1467

Answers (3)

greenoldman
greenoldman

Reputation: 21082

One really 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 is a pity, that for example most methods of string are not extension methods, after all

x.ToLower();

should return null if x is null. I mean, it would be useful.

When I need such null-transparency I prefer writing extension methods.

Upvotes: 3

Josh
Josh

Reputation: 44916

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

At the end of the day Extension methods are some nice compiler magic and syntactic sugar that allow you to invoke a Static method as though it were a method defined on that particular class instance. However, it is NOT an instance method, as the instance of that particular class must be passed into the function.

Upvotes: 7

TalentTuner
TalentTuner

Reputation: 17566

ExtensionMethods : Let you define set of methods to a class without subclassing another benefit over inheritance.

Methods : They are used for implementation of operation defind for the the class.

See example of Extension Methods

Upvotes: 4

Related Questions