We help IT Professionals succeed at work.

Using 'this' statement in static method pros/cons in C#

Hakan used Ask the Experts™

I'm using a static method to get information from COM object like;

public static string GetBodyName(this IScrBody obj) { //some code}

With that i'm able use it like;

var myBodyName = Body.GetBodyName()

in before i'm using like that;

public static string GetBodyName(IScrBody obj) { //some code}

and i'm trying to return a value

var myBodyName = GetBodyName(obj)

Now i've search on net but didn't find like i expected.

Now i'd like to know are there any pros/cons of using this statement.

I really need expert's advice.

Any help would be great!
Thank you.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018
Hi Hakan,

I am bit confused between the question title and the actual question.

If you are anding if you can use "this" keyword in a static class/method, then answer is No.

If thers is something else, then please clarify.



Hi Chinmay,

My question is about difference between them where to use, where to don't use pros/cons

public static string GetBodyName(IScrBody obj) { //some code}
public static string GetBodyName(this IScrBody obj) { //some code}

Open in new window

this IScrBody obj
Architect - Coder - Mentor
The second one is called extension method and can be defined only in a static class. It’s just a syntactic sugar for a function that can do processing over the given object; it’s not part of the object itself.
As you have presented the 2 methods, there is no difference between these two.
Static methods are not bad per se, but they tend to be placed in a wrong place and to have the feature envy smell by requiring too much info about the object that they’re processing. Always think if isn’t a better approach to have the method as part of an object, and if not, why.