Extension methods oddities

Published Thu, Mar 11 2010 13:46

I’m back…I hope…After some complicated times which culminated in the floods which destroyed several regions of Madeira, I guess things are starting to coming back to normal…at least, that’s what I hope…I’ll probably return to blogging, though the rhythm won’t be the same as before.

One of the things I’ve been doing since I’ve migrated my code to C# 3.0 is defining and using extension methods. Another things which I tend *not* to do is use the this for qualifying access to a class’ members. Now, the thing is that *this* is required (ie, not optional) when you want to use an extension method in a class’ body. Suppose you’ve got class A and an extension method called T. Take a look at the following snippet:

class A {
    public void DoSomething() {
        this.T();
    }
}

Since T is an extension method, you do really need to use the *this* qualifier. If you don’t, you’ll end up with a compiler error. I guess this is one of the oddities associated with extension methods (after all, they’re really static methods and we’re talking about a hack which does really help in several scenarios)…

Filed under:

Comments

# Rafael Romão said on Thursday, March 11, 2010 11:33 AM

Welcome back!

For me the main oddity on using Extension Methods, until now, is the need to add a using clause for the namespace which contains the extension methods before to use them. But I see it as the cost to be paid.

But why not to use the "this" qualifier?

What oddities do you see on using it?

# Bertrand Le Roy said on Thursday, March 11, 2010 5:06 PM

Hold on, if you *know* about this extension method to yourself, why is this an extension method in the first place? Why not a simple method? Am I missing something?

# luisabreu said on Monday, March 15, 2010 2:41 PM

Bertrand, I'm following...the method was created for "extending" an existing class and the "problem" (ok, it's not really a problem) happened when someone extended that class (ie, inherited from it) and needed to use the existing method internally. does this explanation gives you the right context?

# Bertrand Le Roy said on Wednesday, March 17, 2010 1:24 AM

Ah, OK, I see. Yes, looks like a reasonable scenario.

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover