Chris Anderson

Chris Anderson

  • NA
  • 93
  • 8.2k

Get property in inerrited class

Jan 13 2021 6:58 PM
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:
  1. public void InitPlay(Toy toy)  
  2. {     
  3.     Console.WriteLine($" The {TypeOfAnimal}{Name} is now playing with the {toy.Color} {toy} ");  
  4. }  
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. 
  1. public void InitPlay(Toy toy)  
  2. {  
  3.    Ball ball = new Ball();  
  4.    Console.WriteLine($" The {TypeOfAnimal}{Name} is now playing with the {ball.Color} {toy} ");  
  5. }  
 

 Rest of the code (if needed)
  1. class Ball : Toy  
  2. {  
  3.     public string Color { getset; }  
  4. }  

  1. abstract class Toy  
  2.     {  
  3.      ...
  4.      }  
 
 
 

Answers (5)