Cast Controls

StewartBW 1,480 Reputation points
2025-04-27T18:47:41.3566667+00:00

Hello all,

Inside a module / sub, I set some properties of controls on various forms, based on the theme:

For Each MyControl As Control In InputForm.Controls
 If TypeOf MyControl Is Label Then
  Dim MyLabel = DirectCast(MyControl, Label)
  MyLabel.BackColor = Color.FromArgb(255, 1, 2, 3)
 End If
 If TypeOf MyControl Is customButton Then ' Inherits Button
  Dim MyButton = DirectCast(MyControl, _ButtonBar)
   MyButton.BackColor = Color.FromArgb(255, 1, 2, 3)
 End If
Next

The problem is that I applied a Ruleset and CodeAnalysisLog.xml contains:

'MyControl', a variable, is cast to type 'blah' multiple times in method. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction.

What am I doing wrong here? How to eliminate the warning?

Thanks :)

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,841 questions
0 comments No comments
{count} votes

Accepted answer
  1. Marcin Policht 45,800 Reputation points MVP Moderator
    2025-04-27T19:36:06.5033333+00:00

    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 get Nothing.
    • 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

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.