Thursday, November 19, 2009

.NET Error: Operator '<operatorname>' is not defined for types '<typename1>' and '<typename2>'

Error Description:

The error "Operator '<operatorname>' is not defined for types '<typename1>' and '<typename2>'" occurs When an attempt was made to use an operator in a way that is inappropriate for the specified types.

Reason:

This error can be caused by using the "=" operator instead of using the Is operator to compare two objects.


 

Example:


 

Private Sub toolBar_ButtonClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs)


If e.Button = toolBarButtonNew
Then ' => Error Operator '=' is not defined for types 'System.Windows.Forms.ToolBarButton' and 'System.Windows.Forms.ToolBarButton'

      menuItemNew_Click(Nothing, Nothing)

End If

 

If e.Button <> toolBarButtonSave
Then ' => Error Operator '<>' is not defined for types 'System.Windows.Forms.ToolBarButton' and 'System.Windows.Forms.ToolBarButton'

menuItemNew_Click(Nothing, Nothing)

End
If

 

End Sub

 

Solutions:

  1. Use Is operator to compare two reference types.
  2. Use the Not operator in conjunction with the Is operator to denote inequality. 

Replace


  1. "If e.Button = toolBarButtonNew
    Then"
    with "If e.Button Is toolBarButtonNew
    Then"

  2. "If e.Button <> toolBarButtonSave
    Then"
    with "If Not e.Button Is toolBarButtonSave
    Then"

No comments:

Post a Comment