I am currently learning to work with abstract classes and virtual. I created a simple form that generates the names of animals, color, and the sound they make. Everything seems to work right except for color display property. The results are being displayed in a multiline textBox. Is there a way to display the result with only the color name instead of this format Color [DarkGray]?
Result when button clicked:
Betty is a Color [DarkGray] horse with four legs and runs very fast that goes neigh! neigh!!
The desired result:
Betty is a Dark Gray horse with four legs and runs very fast that goes neigh! neigh!!
CODE
namespace farm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public abstract class Animal
{
protected string the_name;
protected string the_type;
protected Color the_color;
protected string features;
public virtual string speaks()
{
return "";
}
public override string ToString()
{
string s = the_name + " is a " + the_color + " " + the_type + " with " + features + " that goes " + speaks();
return s;
}
}
public class Horse : Animal
{
public Horse(string new_name, Color new_color)
{
the_name = new_name;
the_color = new_color;
the_type = "horse";
features = "four legs and runs very fast";
}
public override string speaks()
{
return "neigh! neigh!!";
}
}
private void button1_Click(object sender, EventArgs e)
{
Horse horse1 = new Horse("Topaz", Color.DarkGray);
textBox1.AppendText(horse1.ToString());
}
}
}
Yes, in your ToString method, use:
Or better still, if you want to have a string with whitespace in where the string contains upper case characters, e.g. DarkGray => Dark Gray, you could define an extension like this
and call it like this