tags:

views:

106

answers:

3

Quirky question:

Imagine that I have a base class called BaseFoo. I have an interface with some methods called IFoo. And I have tons of classes beneath BaseFoo.

If i implement the interface in BaseFoo, i dont need to implement in the inherited classes, correct?

Ok, but imagine that i have a generic function that will treat IFoo's. Do i need to explicitely declare that they implement IFoo?

Like this (pseudo-illustrational-code)

public class BaseFoo:IFoo;

public interface IFoo;

Should i do this?

public class AmbarFoo:BaseFoo,IFoo

or?

public class AmbarFoo:BaseFoo

What is the most correct way? Are the effects the same? If i test if AmbarFoo is a IFoo what will I get?

Thanks

+7  A: 

It will behave the same way regardless. You'd only need to restate the interface name if you wanted to reimplement the interface with explicit interface implementation. An instance of AmbarFoo will indeed "say" that it implements IFoo.

Jon Skeet
Thanks! Exactly the answer i needed.
Joooohn
I think Jon Skeet should skip questions like this one.
Hamish Grubijan
I think we need a JonSkeetFacts.com site a la http://www.chucknorrisfacts.com/
Gordon Mackie JoanMiro
or ... like http://gb1990.com/
Hamish Grubijan
@Gordon: You're aware of the Jon Skeet Facts question on Meta, right?http://meta.stackoverflow.com/questions/9134/jon-skeet-facts
Jon Skeet
A: 

If i implement the interface in BaseFoo, i dont need to implement in the inherited classes, correct?

No, because BaseFoo will be forced to implement, and the child classes will inherit the implementation. They will all still be IFoos though.

Dave Sims
A: 

In your case it won't change anything.

However, look at the following one:

public interface IFoo
{
    void Bar();
}

public class FooBase
    : IFoo
{
    public void Bar()
    {
        Console.WriteLine("FooBase");
    }
}

public sealed class SubFoo
    : FooBase//, IFoo
{
    public new void Bar()
    {
        Console.WriteLine("SubFoo");
    }
}

Now run the following and comment out the "//, IFoo".

SubFoo foo = new SubFoo();

foo.Bar();
((IFoo) foo).Bar();

However, this is more theoretically.

Leave it away.

winSharp93