Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set a field value in a base class that can be overridden in child classes in C#

I have a C# class that looks like this:

public class Animal
{
  public string _name = "Animal";

  public string GetGreeting()
  {
    if (this._name == "Animal")
    {
      return "Hello friend!";
    }
    else
    {
      return $"Hello, '{this._name}'";
    }
  }
}

public class Tiger : Animal
{
  // How do I set "_name" here?
}

I want to hard-code the _name value in the Tiger class. However, I don’t want to force other classes to set the _name value. How do I do that in C#?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just add a constructor:

public Tiger()
{
    _name = "Tony"; // they're great!
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading