0

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

2
  • 3
    note: public fields are usually a very bad idea - IMO public string Name {get;set;} would be a far better idea Commented Oct 19, 2022 at 14:24
  • Your hierarchy is pretty strange IMHO. What should new Animal() return? I suppose the base-class shouldn't be instantiable. Better make it abstract. Commented Oct 19, 2022 at 14:29

1 Answer 1

2

Just add a constructor:

public Tiger() { _name = "Tony"; // they're great! } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.