You're very close...
The issue is that you're performing two separate DirectCast
calls on the same MyControl
in the same For Each
loop without caching it. Even though you only cast inside an If TypeOf
check, the analyzer sees "multiple casts" and flags it for optimization.
Even though TypeOf...Then
ensures type safety, it's better to use TryCast
once (or cache the DirectCast
) and check for Nothing
. That way you avoid the "redundant cast" warning.
For Each MyControl As Control In InputForm.Controls
Dim MyLabel As Label = TryCast(MyControl, Label)
If MyLabel IsNot Nothing Then
MyLabel.BackColor = Color.FromArgb(255, 1, 2, 3)
Continue For
End If
Dim MyButton As customButton = TryCast(MyControl, customButton)
If MyButton IsNot Nothing Then
MyButton.BackColor = Color.FromArgb(255, 1, 2, 3)
Continue For
End If
Next
-
TryCast
safely attempts the cast — if it's the correct type, you get the object; if not, you getNothing
. - No need for
TypeOf ... Then
+DirectCast
. - Only one cast per control, satisfying both the analyzer and improving runtime performance a little.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin