Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Dubious downcast of ‘this’

ID: cs/downcast-of-thisKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - correctness   - testability   - language-featuresQuery suites:   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

If a typeDerived inherits (either directly or indirectly) from a typeBase, then it has a dependency onBase by virtue of this inheritance relationship - that is, it cannot be used withoutBase also being present. If, in addition to makingDerived inherit fromBase, you also write code that depends onDerived withinBase, you causeBase to depend onDerived as well, resulting in a dependency cycle between the two types. Dependency cycles are a well-known design smell, in that they make code both difficult to read and difficult to test.

In the situation just described, the dependency cycle has been introduced by writing code that coerces the type ofthis to a derived type. This is a very unwise thing to do - a type should never know about its specific descendants, even though it may of course choose to impose some constraints on them as a group (such as the need for every derived type to implement a method with a specific signature).

Recommendation

The appropriate solution to this problem is to redesign the base and derived types so that there is no longer a need for the base type to depend on the types that derive from it.

Example

In this exampleBaseClass attempts to downcast itself to various known subclasses in order to call methods specific to those subclasses. This is very bad practice.

classDubiousDowncastOfThis{classBaseClass{publicintdoAnything(intx){DerivedAa=thisasDerivedA;if(a!=null)returna.doSomething(x);DerivedBb=thisasDerivedB;if(b!=null)returnb.doSomethingElse(x);return0;}}classDerivedA:BaseClass{publicintdoSomething(intx){returnx+5;}}classDerivedB:BaseClass{publicintdoSomethingElse(intx){returnx+10;}}}

[8]ページ先頭

©2009-2025 Movatter.jp