wpfnoop wpfnoop - 3 months ago 7
C# Question

A proper way of defining methods strongly connected to the interface

I have a following interface:

interface IName
{
string Name { get; }
}


And some base class BaseClass. Childs of this class may implement IName interface, but not all of them do.

If a Child implements IName, I would also like to override ToString() method, exactly the same way for all cases, as follows:

public override string ToString()
{
return Name;
}


It seems that a good place for overriding ToString() would be in IName interface, but i believe that it is not possible in C#.
Implementing ToString() in every class seems a bad idea too, because it's a lot of code redundancy (and a waste of time).

What is a proper solution for a case like this?

Answer

I'd suggest to make a second base class as such:

public abstract class BaseClass
{
    // your base class implementation
}

public abstract class NamedBaseClass : BaseClass, IName
{
    public string Name { get; set;}
    public override string ToString()
    {
        return Name;
    }
}

this way, if you want a child to implement both BaseClass and IName, then you should inherit from NamedBaseClass. According to your words that "some might implement IName and some not", then BaseClass should not implement IName, but you should still have some sort of a base implementation. this is my solution.

EDIT:

to make a single class which returns the name and has nothing to do with BaseClass, then you can make an unrelated abstract implementation just for that:

public abstract class NameStringClass : IName
{
     public string Name { get; set; }
     public override string ToString()
     {
          return Name;
     }
}
Comments