Chris Anderson

Chris Anderson

  • NA
  • 93
  • 8.3k

Cast is redundant. How to use the is statement?

Dec 2 2020 2:14 AM
Why is it saying "Cast is redundant"? If I remove the cast it instead says How can I target and use the is statement "toy is Featuer feather" otherwise?
 
Working example: Only says "Cast is redundant" by doesn't through any errors.
  1. if (input == 1 && (object)toy is Feather feather)  
  2. {  
  3.     Console.WriteLine("ba");  
  4.     typeOfToy = feather;  
  5. }  
Working example: Foreach lets me target the "toy is Feather feather" without any errors. But putting every is statement in a foreach seems overkill?
  1. foreach (var toy in this.toy)  
  2. {  
  3.     if (input == 1 && toy is Feather feather)  
  4.     {  
  5.         Console.WriteLine("ba");  
  6.         typeOfToy = feather;  
  7.     }  
  8. }
Not working example: Casting (object) has been removed and through: "An expression of type List cannot be handled by a pattern of type 'Feather'. Why is that and what's the best practise using my two examples above? Any other ways to solve this?
  1. if (input == 1 && toy is Feather feather)  
  2. {  
  3.     Console.WriteLine("ba");  
  4.     typeOfToy = feather;  
  5. }

Answers (3)