Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Missed opportunity to use Cast

ID: cs/linq/missed-castKind: problemSecurity severity: Severity: recommendationPrecision: highTags:   - quality   - maintainability   - readability   - language-featuresQuery suites:   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

Casts are often used when you iterate over a collection of elements of a type that is known to contain only elements of a different type (possibly more specific). For example,List<Animal> might refer to a collection of instances ofDog, a class derived fromAnimal. Programmers often write a loop to iterate over the collection and cast eachAnimal in turn toDog before using it

Recommendation

This pattern works well and is also available as theCast method in LINQ. It is better to use a library method in preference to writing your own pattern unless you have a specific need for a custom version. In particular, this makes the code easier to read by expressing the intent better and reducing the number of distinct variables in scope within the loop. It is important to remember that Cast will throw a InvalidCastException if any of the elements cannot be cast. (If you are not sure that all of the elements have the expected type, and you only want to operate on the ones that do, then consider usingOfType instead.)

Example

In this example, each element in the array ofAnimal’s is cast toDog.

classMissedCastOpportunity{classAnimal{}classDog:Animal{privatestringname;publicDog(stringname){this.name=name;}publicvoidWoof(){Console.WriteLine("Woof! My name is "+name+".");}}publicstaticvoidMain(string[]args){List<Animal>lst=newList<Animal>{newDog("Rover"),newDog("Fido"),newDog("Basil")};foreach(Animalainlst){Dogd=(Dog)a;d.Woof();}}}

This could be written better using LINQ’s cast method to cast the whole list and then iterate over that.

classMissedCastOpportunityFix{classAnimal{}classDog:Animal{privatestringname;publicDog(stringname){this.name=name;}publicvoidWoof(){Console.WriteLine("Woof! My name is "+name+".");}}publicstaticvoidMain(string[]args){List<Animal>lst=newList<Animal>{newDog("Rover"),newDog("Fido"),newDog("Basil")};foreach(Dogdinlst.Cast<Dog>()){d.Woof();}}}

References


[8]ページ先頭

©2009-2025 Movatter.jp