سؤال

I have a IEquatable<T> method thus:

public bool Equals(TravelOptions other)
{
    if (other == null) return false;
    return 
        this.OutTravelType.Equals(other.OutTravelType) &  //enum
        this.BackTravelType.Equals(other.BackTravelType) & //enum
        this.OutTravelPointID.Equals(other.OutTravelPointID) & //int
        this.BackTravelPointID.Equals(other.BackTravelPointID) & //int
        this.OutTerminal.Equals(other.OutTerminal) & //string
        this.BackTerminal.Equals(other.BackTerminal) & //string
        this.OutTime.Equals(other.OutTime) & //string :(
        this.BackTime.Equals(other.BackTime) & //string
        this.Checkin.Equals(other.Checkin) & //int
        this.OutFree.Equals(other.OutFree) & //bool
        this.BackFree.Equals(other.BackFree); //bool
}

but what I need to do is add some checks for nulls for various bits in there, as currently it will throw a nullreferenceexception is there some cunning way of doing that so it doesn't end up being a nasty mess? the out and back travel types are enums and are always set so checking those first. the out and back free are bools, and the travelpoints are ints, all the rest are strings. just feel it will get awfully messy if i start having to check for nulls, unless there is some shorthand way of doing that?

thanks

هل كانت مفيدة؟

المحلول

For all of those properties, just use == instead of calling Equals:

return OutTravelType == other.OutTravelType &&
       BackTravelType == other.BackTravelType &&
       ...;

All of those types are either handled directly (int, bool, enum) or have overloaded == operators (string). Note the use of && instead of &, as && is short-circuiting: there's no point in checking the other 10 properties if the first one compares non-equal.

As an aside, it looks like you could encapsulate all the "Out" properties together and all the "Back" properties together, leaving you with just:

return OutwardJourney == other.OutwardJourney &&
       ReturnJourney == other.ReturnJourney &&
       Checkin == other.Checkin; // Looks like this isn't part of out/back

where a Journey would have a travel type, travel point ID, terminal, time and "free" (whatever that means).

نصائح أخرى

You can use the static form of string.Equals that handles null values gracefully:

string.Equals(this.OutTerminal, other.OutTerminal)

Of course if you don't intend to provide options through StringComparison this is simply the same as if comparing with ==.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top