Search code examples
c#abstract-class

Abstract class cast issue


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?


Solution

  • 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.