Skip to content

Commit d3e3603

Browse files
authored
Merge pull request #8152 from tamasvajk/fix/useless-dynamic-cast
C# Exclude dynamic casts from useless casts check
2 parents d953382 + efb8761 commit d3e3603

File tree

3 files changed

+22
-8
lines changed

3 files changed

+22
-8
lines changed

csharp/ql/src/Language Abuse/UselessUpcast.ql

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,8 @@ class ExplicitUpcast extends ExplicitCast {
204204
this = any(LocalVariableDeclAndInitExpr decl | decl.isImplicitlyTyped()).getInitializer()
205205
or
206206
exists(LambdaExpr c | c.canReturn(this))
207+
or
208+
dest instanceof DynamicType
207209
}
208210
}
209211

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
category: minorAnalysis
3+
---
4+
* Casts to `dynamic` are excluded from the useless upcasts check (`cs/useless-upcast`).

csharp/ql/test/query-tests/Language Abuse/UselessUpcast/UselessUpcast.cs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ public void M(A a) { }
1717

1818
class B : A
1919
{
20-
public static bool operator==(B b1, B b2) { return false; }
21-
public static bool operator!=(B b1, B b2) { return true; }
20+
public static bool operator ==(B b1, B b2) { return false; }
21+
public static bool operator !=(B b1, B b2) { return true; }
2222
public void M(B b) { }
2323
}
2424

@@ -68,11 +68,11 @@ void Test1(string[] args)
6868

6969
((I2)a).Foo(); // GOOD: Cast to an interface
7070

71-
o = a==(A)b; // GOOD: EQExpr
71+
o = a == (A)b; // GOOD: EQExpr
7272

73-
o = b==(B)b; // GOOD: Operator call
73+
o = b == (B)b; // GOOD: Operator call
7474

75-
var act = (Action) (() => { }); // GOOD
75+
var act = (Action)(() => { }); // GOOD
7676

7777
var objects = args.Select(arg => (object)arg); // GOOD
7878

@@ -126,9 +126,9 @@ public static void M2(this I3 i) =>
126126

127127
static class StaticMethods
128128
{
129-
public static void M1(A _) { }
130-
public static void M1(B _) { }
131-
public static void M2(B _) { }
129+
public static void M1(A _) { }
130+
public static void M1(B _) { }
131+
public static void M2(B _) { }
132132
}
133133

134134
class Constructors : I2
@@ -162,4 +162,12 @@ void M(SubSub ss)
162162
new Sub((Sub)ss); // BAD
163163
}
164164
}
165+
166+
class Dynamic
167+
{
168+
void M(object o)
169+
{
170+
var s0 = ((dynamic)o).ToString(); // GOOD
171+
}
172+
}
165173
}

0 commit comments

Comments
 (0)