I'm trying to cast an object that's being passed into a method to one of its inherited classes/objects.
Since I want to prevent duplicated code as far as possible. Last example is the working one and maybe the best solution even though it has duplicated text blocks?
What's your thoughts on this in general? How would you have done it?
Example 1 - Not working one but the prefered one
Using this would leave me only with one block of texts i.e. "The ... is not playing with..."
toy is never casted to ball (as I was hoping and expected) however. Thus let me access the property Color from Ball.
Example 2 - Working one but with duplicated text blocks
Since I want to prevent duplicated code as far as possible. Last example is the working one and maybe the best solution even though it has duplicated text blocks?
What's your thoughts on this in general? How would you have done it?
Example 1 - Not working one but the prefered one
Using this would leave me only with one block of texts i.e. "The ... is not playing with..."
toy is never casted to ball (as I was hoping and expected) however. Thus let me access the property Color from Ball.
C#:
public void InitPlay(Toy toy)
{
if (toy is Ball ball)
{
toy = (Ball)toy; // At this point I was expecting toy to be casted to the Ball object...
}
else if (toy is Bone bone)
{
toy = (Bone)toy; // At this point I was expecting toy to be casted to the Bone object...
}
Console.WriteLine($"\n - Press enter to start playing with the {toy}");
Console.ReadLine();
Console.WriteLine(" --------------------------------------------------------");
// ... and thus be able to reach Color in the Ball object using toy.Color. With no luck.
Console.WriteLine($" The {TypeOfAnimal}{Name} is now playing with the {toy.Color} {toy} ");
Console.WriteLine(" - Press enter to finish playing ");
Console.WriteLine(" --------------------------------------------------------");
}
Example 2 - Working one but with duplicated text blocks
C#:
public void InitPlay(Toy toy)
{
Console.WriteLine($"\n - Press enter to start playing with the {toy}");
Console.ReadLine();
if (toy is Ball ball)
{
// This forces me to have more or less duplicated blocks of text just to reach properties from each inherited object.
Console.WriteLine(" --------------------------------------------------------");
Console.WriteLine($" The {TypeOfAnimal}{Name} is now playing with the {ball.Color} {toy} ");
Console.WriteLine(" - Press enter to finish playing ");
Console.WriteLine(" --------------------------------------------------------");
}
if (toy is Bone bone)
{
Console.WriteLine(" --------------------------------------------------------");
Console.WriteLine($" The {TypeOfAnimal}{Name} is now playing with the {bone.Size} {toy} ");
Console.WriteLine(" - Press enter to finish playing ");
Console.WriteLine(" --------------------------------------------------------");
}
}