Resolved VS2010 Check if Object is a Color

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,530
Location
Lansing, MI; USA
Programming Experience
10+
I'm curious to know if there's a good way to see if an object is a System.Drawing.Color before I try casting it to one. Right now it seems the only way I can do that is to put it in a Try/Catch block and if it hit's the catch part then I know the object isn't a color. Here's my code so far:
VB.NET:
    Protected Overrides Sub onDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
        e.DrawBackground()
        e.DrawFocusRectangle()
        If e.Index > -1I AndAlso Me.Items.Count > 0I Then
            ' Get the Color object from the Items list
            Dim br As Brush = If((e.State And DrawItemState.Selected) = DrawItemState.Selected, Brushes.White, Brushes.Black)
            Try
                Dim aColor As Color = CType(Me.Items(e.Index), Color)

                ' get a square using the bounds height
                Dim rect As Rectangle = New Rectangle(5I, e.Bounds.Top + 2I, e.Bounds.Height - 3I, e.Bounds.Height - 5I)

                ' draw a rectangle and fill it
                e.Graphics.DrawRectangle(New Pen(aColor), rect)
                e.Graphics.FillRectangle(New SolidBrush(aColor), rect)
                ' draw a border
                rect.Inflate(1I, 1I)
                e.Graphics.DrawRectangle(Pens.Black, rect)

                ' draw the Color name
                e.Graphics.DrawString(aColor.Name, Me.Font, br, e.Bounds.Height + 5I, ((e.Bounds.Height - Me.Font.Height) \ 2I) + e.Bounds.Top)
            Catch
                'Not a color, skip the drawing of a square
                e.Graphics.DrawString(Me.Items(e.Index).ToString, Me.Font, br, e.Bounds.Height + 5I, ((e.Bounds.Height - Me.Font.Height) \ 2I) + e.Bounds.Top)
            End Try
        End If
    End Sub
I really don't like this because there's a slight flicker while it fires up the Exception handling and I would really rather use an If Else End If for this than a Try/Catch.
 
I've answered this for JB at another forum but, for the benefit of others...

Generally speaking, you have two options:
VB.NET:
Private Sub SomeMethod(arg As Object)
    Dim var = TryCast(arg, SomeType)

    If var IsNot Nothing Then
        'Use var here.
    End If
End Sub
VB.NET:
Private Sub SomeMethod(arg As Object)
    If TypeOf arg Is SomeType Then
        Dim var = DirectCast(arg, SomeType)

        'Use var here.
    End If
End Sub
The TryCast option only works with reference types though. As Color is a value type, you'll have to go with the TypeOf option.
 
Back
Top