Assignment in an if statement
问题 I have a class Animal , and its subclass Dog . I often find myself coding the following lines: if (animal is Dog) { Dog dog = animal as Dog; dog.Name; ... } For the variable Animal animal; . Is there some syntax that allows me to write something like: if (Dog dog = animal as Dog) { dog.Name; ... } 回答1: The answer below was written years ago and updated over time. As of C# 7, you can use pattern matching: if (animal is Dog dog) { // Use dog here } Note that dog is still in scope after the if