Dillinger Dillinger - 5 years ago 117
Vb.net Question

How to define '=' for own class?

I created a class like this:

Public Class WorkDay

Public Property starttime As String = Nothing
Public Property endtime As String = Nothing
Public Property breaks As New List(Of Break)

End Class

Now I need to compare an object of this class, for example this:

Dim working_plan = JsonConvert.DeserializeObject(Of Dictionary(Of String, WorkDay))(wp)
Dim DayNames = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
Dim this_day = working_plan(day)

If this_day = Nothing Then

is an object of
class, so when I try to compare to nothing, I get:

The operator = is not defined for

I should define the operator in my own class? How I can do that?

Answer Source

EDIT: Edit says that I should read the question carefully before answering questions ;) To check whether an object is Nothing you have to use the Is repsective IsNot key words:

    If this_day Is Nothing Then


   If this_day IsNot Nothing Then

Original answer of comparing objects which are not nothing:

Overload the equal operator in your WorkDay class:

Public Shared Operator =(x As WorkDay, y As WorkDay)
       'Code to determine whetther x equals y
End Operator

Be aware that you also have to overload the not equals operator:

Public Shared Operator <>(x As WorkDay, y As WorkDay)
      'Code to determine whetther x not equals y
End Operator

In resepect of Magnus comment:

Public Overrides Function Equals(obj As Object) As Boolean
    Dim o As WorkDay = TryCast(obj, WorkDay)
    If o IsNot Nothing Then
        'check whether o equals Me
        Return False
    End If
End Function

Public Overrides Function GetHashCode() As Integer
    'return a feasible hashcode of a member of Me e.g.
     Return Me.StartTime.GetHashCode() XOR Me.EndTime.GetHashCode() 
End Function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download