The error is thrown by your equality operator. You are calling a method on both operands, without testing whether they are
null
first. And since your type is a reference type, one or both sides could be
null
.
(You'll have the same problem with your implicit datetime
to long
conversion operator - the datetime
parameter could be null
, and you'll get a NullReferenceException
.)
You could fix your operator:
public static bool operator ==(datetime datetimeLeftSide, datetime datetimeRightSide)
{
if (datetimeLeftSide is null) return datetimeRightSide is null;
if (datetimeRightSide is null) return false;
return datetimeLeftSide.GetValue() == datetimeRightSide.GetValue();
}
But you should really be providing the full set of equality methods:
public class datetime : IEquatable<datetime>
{
...
public override int GetHashCode()
{
return value.GetHashCode();
}
public override bool Equals(object obj)
{
return Equals(obj as datetime);
}
public bool Equals(datetime other)
{
if (other is null) return false;
return other.value == this.value;
}
public static bool operator ==(datetime left, datetime right)
{
return Equals(left, right);
}
public static bool operator !=(datetime left, datetime right)
{
return !Equals(left, right);
}
...
}
NB: If you want the values to be filled automatically, you would need to create a value type instead:
Structure types - C# reference | Microsoft Docs[
^]
However, you would not be able to have a default value of
-1
for the field.
public readonly struct datetime : IEquatable<datetime>
{
private readonly long value;
public datetime(long value)
{
this.value = value;
}
public long GetValue()
{
return value;
}
public override int GetHashCode()
{
return value.GetHashCode();
}
public override bool Equals(object obj)
{
return obj is datetime other && Equals(other);
}
public bool Equals(datetime other)
{
return other.value == this.value;
}
public static bool operator ==(datetime left, datetime right)
{
return Equals(left, right);
}
public static bool operator !=(datetime left, datetime right)
{
return !Equals(left, right);
}
public static implicit operator datetime(long value)
{
return new datetime(value);
}
public static implicit operator long(datetime first)
{
return first.value;
}
}