views:

63

answers:

1

Apparently, extension methods don't work on subclasses, or is it just me?

private class Parent
{        
}

private class Child
{
}

public static class Extensions
{
    public static void Method(this Parent parent)
    {
    }
}

//Test code
var p = new Parent();
p.Method();            // <--- compiler like
var c = new Child();
c.Method();            // <--- compiler no like

UPDATE

There is a typo in this question (which I'm leaving so that the rest makes sense) - I forgot to make Child inherit from Parent.

As it happens, my real problem was that I didn't have the appropriate using statement.

(Unfortunately, I can't delete, as too many upvotes on answer.)

+7  A: 

This should work just fine (LINQ extensions are built on top of IEnumerable<T>, and they work on List<T> et al.). The issue is that Child does not inherit from Parent in your example.

Chris Schmich
Yes. Benjoi, can we assume a typo or is this the answer?
Henk Holterman
Indeed, adding `Child : Parent` makes it all work
Marc Gravell
OK, my bad :( Typo indeed. The thing is, this was demo code to try and reproduce the problem for the question's sake. But in the real code, it doesn't work. *Back to the coalface...* (Should I just delete the question?)
Benjol
@Benjol: Yes, if you can. Feel free to ask a new question though, with an example that reproduces the problem.
Timwi
@Benjol, complier checks extension methods only in types available in current scope - check your references and namespaces (using directives). Perhaps type implementing extension method is simply not in reference scope where you want to use it.
VinayC
@Henk, @Marc, I'd forgotten the `using` - or rather, I'd already included it in one source file, and with intervening interruptions I'd confused which file...
Benjol
@VinayC, yes, in a word :)
Benjol