I'm trying to get the property from an inherited class without creating a new instance and rather use the parameter being passed in the method.
How can I get the property Color over here?
Does not work:
- public void InitPlay(Toy toy)
- {
- Console.WriteLine($" The {TypeOfAnimal}{Name} is now playing with the {toy.Color} {toy} ");
- }
Works:
This one works. But that's just because I created a new object of class Ball. But the point of passing in toy is thus redundant.
This one works. But that's just because I created a new object of class Ball. But the point of passing in toy is thus redundant.
- public void InitPlay(Toy toy)
- {
- Ball ball = new Ball();
- Console.WriteLine($" The {TypeOfAnimal}{Name} is now playing with the {ball.Color} {toy} ");
- }
Rest of the code (if needed)
- class Ball : Toy
- {
- public string Color { get; set; }
- }
- abstract class Toy
- {
- ...
- }

Sachin SinghRank #66 · 26.2K reputationPosted Jan 13, 2021, 2:34 PM EST
Ben ThompsonRank #8,839 · 215 reputationPosted Jan 13, 2021, 5:49 PM EST
Ben ThompsonRank #8,839 · 215 reputationPosted Jan 14, 2021, 9:06 AM EST
Chris Anderson137 reputationPosted Jan 13, 2021, 3:55 PM EST
From the example below. How do I proceed? Is there any best practises on what I'm trying to achieve?
Here the variable selectedToy is assigned to ball and put into the method InitPlay()...
Chris Anderson137 reputationPosted Jan 13, 2021, 6:41 PM EST