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

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Exactly the answer i needed.
I think Jon Skeet should skip questions like this one.
@Gordon: You're aware of the Jon Skeet Facts question on Meta, right? meta.stackexchange.com/questions/9134/jon-skeet-facts
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.