tags:

views:

1501

answers:

6

Say I have an interface IFoo, and I want all subclasses of IFoo to override Object's ToString method. Is this possible?

Simply adding the method signature to IFoo as such doesn't work:

interface IFoo
{
    String ToString();
}

...since all the subclasses extend Object and provide an implementation that way, so the compiler doesn't complain about it. Any suggestions?

Edit: fixed title

+11  A: 

I don't believe you can do it with an interface. You can use an abstract base class though:

public abstract class Base
{
    public abstract override string ToString(); 
}
Jon Skeet
I was hoping stick with interfaces since I've already gotten them written, guess I'll have to bite the bullet and switch abstract classes. Thanks.
rjohnston
+12  A: 
abstract class Foo
{
    public override abstract string ToString();
}

class Bar : Foo
{
    // need to override ToString()
}
Andrew Peters
Question was "can I do this with an interface?", not "how do I do this?", but thanks anyway.
rjohnston
A: 

I don't think you can force any sub-class to override any of the base-class's virtual methods unless those methods are abstract.

Frederick
A: 

Implementing an interface method implicitly seals the method (as well as overriding it). So, unless you tell it otherwise, the first implementation of an interface ends the override chain in C#.

Essential .NET

Abstract class = your friend

Check this question

Ric Tokyo
A: 

You can override in a subclass but there are some gotchas.

    
interface IFoo
{
    void Bar();
}

class Foo : IFoo
{
    public void Bar()
    {
        //Do some stuff
    }
}

class SubFoo : Foo, IFoo
{
    void IFoo.Bar()
    {
        //Do some other stuff
    }
}

class UseFoo
{
    Foo foo;
    SubFoo subFoo;
    IFoo iFoo;

    UseFoo()
    {
        foo.Bar();
        subFoo.Bar(); //CAUTION: Actually calls foo.Bar();
        iFoo = subFoo;
        iFoo.Bar(); //Calls the overridden version of Bar();
    }
}

credit goes to this guy:

http://www.williamcaputo.com/archives/000138.html

good luck!

A: 

Jon & Andrew: That abstract trick is really useful; I had no idea you could end the chain by declaring it as abstract. Cheers :)

In the past when I've required that ToString() be overriden in derived classes, I've always used a pattern like the following:

public abstract class BaseClass
{
    public abstract string ToStringImpl();

    public override string ToString()
    {
        return ToStringImpl();
    }    
}
Mark Simpson