user1765862
user1765862

Reputation: 14165

childclass should use parent's ToString()

I have a base class Sport defined as:

public class Sport
{
   public int Id {get; set;}
   public string Name {get; set;}

   public Sport() {}

   public override string ToString()
   {
     string objectState = string.Format("[Id: {0}; Name: {1};]", Id, Name);
     return objectState;
   }
}

and I have second class which inherits the Sport class:

public class Basketball : Sport
{
   public string PointTerm {get; set;}
   public Basketball() {}      

   //overriding ToString()??
}

How do I override ToString from my base Sport class with an additional property PointTerm?

Upvotes: 0

Views: 567

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62002

I'm not sure if this is a good solution in your case (or in any case), but of course it's possible to find all properties defined on your type (whether it be Sport, Basketball or some other derived type) using reflection.

Maybe if you write like this inside your Sport class:

public sealed override string ToString()
{
    var allStrings = GetType().GetProperties()
        .Select(p => p.Name + ": " + p.GetValue(this, null));
    return "[" + string.Join("; ", allStrings) + ";]";
}

Then Sport and all types deriving from it will have ToString defined the same way, and it will use reflection to find all (public) properties.

Upvotes: 0

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20640

You can just add a new override in your Basketball class:

public override string ToString()
{
    return string.Format("[Id: {0}; Name: {1}; PointTerm: {2};]",
                         Id, Name, PointTerm);
}

Edit:

You could do something like this if you want to keep in sync with the base class's implementation, but the simpler approach above is probably better in most circumstances:

public override string ToString()
{
    char[] openingBracket = new char[] { '[' };
    char[] closingBracket = new char[] { ']' };     

    string trimmedBaseString = (base.ToString() ?? string.Empty)
                               .TrimStart(openingBracket).TrimEnd(closingBracket);
    return string.Format("[{0} PointTerm: {1};]", trimmedBaseString, PointTerm);
}

Upvotes: 3

Related Questions