Equality and Assignment Operators

I have an assembly compiled in VB.NET that contains two statements:

Public Shared Operator =(quarterA As CalendarQuarter, quarterB As CalendarQuarter) As Boolean Return quarterA.StartDate = quarterB.StartDate AndAlso quarterA.EndDate = quarterB.EndDate AndAlso quarterA.Quarter = quarterB.Quarter End Operator Public Shared Operator <>(quarterA As CalendarQuarter, quarterB As CalendarQuarter) As Boolean Return Not (quarterA = quarterB) End Operator 

However, when using assembly in C # to perform equality checks if (qtr != null) I get an error:

Cannot implicitly convert type 'object' to 'bool'

Usage in C # MVC4, Razor:

 @{Html.BeginForm();} <div class="ui-form ui-form-horizontal form-width-narrow"> <div class="title"> Choose a Quarter</div> <div class="group"> <label><strong>Control</strong></label> <div class="field"> @Html.DropDownListFor(x => x.Quarter, new SelectList(Model.AvailableQuarters)) <input value="Select" class="ui-button" type="submit" /> </div> </div> @if (Model.Quarter != null) { // Error in the above statement } </div> @{Html.EndForm();} 

What do I need to do to make the equality operator behave correctly?

+4
source share
2 answers

When I implement your as-is code and compare the instance with null, I get a NullReferenceException in your equality statement. However, if I add a null check, it works fine:

 Public Shared Operator =(quarterA As CalendarQuarter, quarterB As CalendarQuarter) As Boolean If quarterA Is Nothing OrElse quarterB Is Nothing Then Return False Return quarterA.StartDate = quarterB.StartDate AndAlso quarterA.EndDate = quarterB.EndDate AndAlso quarterA.Quarter = quarterB.Quarter End Operator 

I suspect something else is causing the error you are getting.

Most likely you are using the assignment operator ( = ) when you should use the equality operator ( == ):

 if (qtr = null) // wrong - assigning null to qtr if (qtr == null) // correct 

Also, I would recommend overriding Equals and GetHashCode to match your equality operator.

+3
source

You cannot overload assignment operators in either VB or C #.

http://msdn.microsoft.com/en-us/library/8edha89s.aspx

0
source

Source: https://habr.com/ru/post/1445887/


All Articles