I have an assembly compiled in VB.NET that contains two operators:
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 the assembly in C# to perform equality checks if (qtr != null) I receive the 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 properly?
When I implement your code as-is and compare an instance to null I get a
NullReferenceExceptionin your equality operator. However if I add a null check it works fine:I suspect something else is causing the error you’re getting.
Most likely you’re using the assignment operator (
=) when you should be using the equality operator (==):In addition, I would recommend overriding
EqualsandGetHashCodeto be consistent with your equality operator.