Given the following code:
class Program
{
static void Main(string[] args)
{
var dog = new Dog();
var cat = new Cat();
dog.Print();
cat.Print();
Console.ReadKey();
}
}
public abstract class Animal
{
private static string _name;
protected Animal(string name)
{
_name = name;
}
private static string _hi;
private string SayHi()
{
return _hi ?? (_hi = $"Hi, i'm a {_name}!");
}
public void Print()
{
Console.WriteLine($"{this.GetType().Name} says: {SayHi()}");
}
}
public class Cat : Animal
{
public Cat() : base("Cat")
{
}
}
public class Dog : Animal
{
public Dog() : base("Dog")
{
}
}
The following output is produced:
Dog says: Hi, i'm a Cat!
Cat says: Hi, i'm a Cat!
Why? I would expect the Dog to say "Hi, i'm a Dog!"
Can someone a) explain to me this behaviour and b) let me know how i should update my code?
The real example is that i'm sharing an expensive property between concrete classes.