0

I have this code:

public abstract class Animal
{
    public string Name { get; set; }
}

public class Dog : Animal
{
    [JsonProperty("name")]
    public new string Name { get; set; }
}

public static void Main()
{
    var dog = new Dog
    {
        Name = "Spark"
    };

    Console.WriteLine(dog.Name);
    Console.WriteLine(((Animal)dog).Name == null);
}

Which will output:

Spark
True

Why is the Name property null when casting it to Animal?

How to fix it, if I want to cast my object to Animal? How can I keep the properties values?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Matt
  • 83
  • 2
  • 9
  • Delete `Name` in `Dog`. Why did you put it there in the first place? – Sweeper Dec 05 '19 at 06:51
  • @Sweeper Updated my example, added ``JsonPropertyAttribute``, I want it to differ depending on the animal (Dog, Cat) so it isn't always ``name`` – Matt Dec 05 '19 at 06:52
  • 1
    Well you never set the base name at all, you are just hiding the base property with the new keyword – arynaq Dec 05 '19 at 06:53
  • 2
    Right, then change `new` to `override`, and make `Animal.Name` virtual. – Sweeper Dec 05 '19 at 06:53

2 Answers2

3

What you expect is implemented by override, so you have to override property:

public override string Name { get; set; }

But in order to do that, you need mark that property as abstract, otherwise you will get an error:

error CS0506: 'Dog.Name': cannot override inherited member 'Animal.Name' because it is not marked virtual, abstract, or override

Refer to this post. There you can read:

The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
1
public class Dog : Animal
{
     string name = null;
     public new string Name { get { return name; } set { name = value; base.Name = name; } } }
}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171