Developer
Developer

Reputation: 317

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#?

Upvotes: 0

Views: 293

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064014

Just add a constructor:

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

Upvotes: 1

Related Questions