r/csharp • u/Chelonii64 • 7h ago
Help Automatically cast a parent property to the child class given in the constructor
in this situation, in the class CatPerson, i would have to manually do ((Cat)pet).catProperty in each method i'd want to use it
i wonder if it's possible to avoid having to manually cast it, is there a way to say something like: in this class, the parent property "pet" must be considered as being of class "Cat" instead of just "Animal"
public class Animal
{
//stuff
}
public class Cat: Animal
{
public string catProperty;
}
public class Person
{
public Animal pet;
public Person(Animal pet) {
this.pet = pet;
}
}
public class CatPerson : Person
{
public CatPerson(Cat pet) : base(pet) //=> give type Cat in constructor
{
}
public void doStuff()
{
// pet.catProperty => pet is not seen as a type "Cat" without casting
}
}