HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Comparing two objects having two nullable date fields

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
comparingobjectsfieldshavingdatenullabletwo

Problem

ExpiryDates has two properties PSL_ExpiryDate and MNL_ExpiryDate of type nullable date. I am trying to compare two objects for having same or different values.

Is there a cleaner way to do the same as the code below?

private bool SameValues(ExpiryDates ExpiryDates1, ExpiryDates ExpiryDates2)
    {
        //Assume they are the same value and the look for differences
        bool result = true;

        if (ExpiryDates1.PSL_ExpiryDate.HasValue != ExpiryDates2.PSL_ExpiryDate.HasValue)
        {
            result = false;
        }

        if (ExpiryDates1.MNL_ExpiryDate.HasValue != ExpiryDates2.MNL_ExpiryDate.HasValue)
        {
            result = false;
        }

        if ((ExpiryDates1.MNL_ExpiryDate != null) && (ExpiryDates2.MNL_ExpiryDate != null))
            if (ExpiryDates1.MNL_ExpiryDate.Value != ExpiryDates2.MNL_ExpiryDate.Value)
                result = false;

        if ((ExpiryDates1.PSL_ExpiryDate != null) && (ExpiryDates2.PSL_ExpiryDate != null))
            if (ExpiryDates1.PSL_ExpiryDate.Value != ExpiryDates2.PSL_ExpiryDate.Value)
                result = false;

        return result;
    }


The ExpiryDate class looks like this:

public class ExpiryDates
{
    public DateTime? MNL_ExpiryDate { get; set; }
    public DateTime? PSL_ExpiryDate { get; set; }
}

Solution

Nullable already does the hard work for you. Just override Equals on your ExpiryDates class (and GetHashCode):

public override bool Equals(object obj)
{
    var otherDates = obj as ExpiryDates;

    return otherDates != null 
        && MNL_ExpiryDate.Equals(otherDates.MNL_ExpiryDate) 
        && PSL_ExpiryDate.Equals(otherDates.PSL_ExpiryDate);
}


As pointed out by mjolka in a comment. It would be advisible to implement IEquatable (IEquatable) as well. See the documentation for why it's a useful thing to do.

Further edit... It does say in the comments for IEquatable but you should additionally override == and != e.g.

public static bool operator ==(ExpiryDates left, ExpiryDates right)
{
    if (object.ReferenceEquals(left, null))
    {
        return object.ReferenceEquals(right, null);
    }
    return left.Equals(right);
}

Code Snippets

public override bool Equals(object obj)
{
    var otherDates = obj as ExpiryDates;

    return otherDates != null 
        && MNL_ExpiryDate.Equals(otherDates.MNL_ExpiryDate) 
        && PSL_ExpiryDate.Equals(otherDates.PSL_ExpiryDate);
}
public static bool operator ==(ExpiryDates left, ExpiryDates right)
{
    if (object.ReferenceEquals(left, null))
    {
        return object.ReferenceEquals(right, null);
    }
    return left.Equals(right);
}

Context

StackExchange Code Review Q#95408, answer score: 9

Revisions (0)

No revisions yet.