Created
April 10, 2018 19:55
-
-
Save hkakutalua/96b0c01f32a8ac7b8fa82d7f19f6a285 to your computer and use it in GitHub Desktop.
Phone number with equality
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Globalization; | |
| namespace Taksapp.Domain.ValueObjects | |
| { | |
| public class PhoneNumber : ValueObject<PhoneNumber> | |
| { | |
| public static readonly PhoneNumber NoPhoneNumber = new PhoneNumber(); | |
| public int RegionCode { get; protected set; } | |
| public string Number { get; protected set; } | |
| public PhoneNumber(int regionCode, string number) | |
| { | |
| if (regionCode < 1 || regionCode > 441624) | |
| throw new ArgumentOutOfRangeException(nameof(regionCode)); | |
| try | |
| { | |
| int.Parse(number, NumberStyles.None); | |
| } | |
| catch (Exception e) | |
| { | |
| throw new ArgumentException(nameof(number), e); | |
| } | |
| RegionCode = regionCode; | |
| Number = number; | |
| } | |
| // For persistence | |
| protected PhoneNumber() | |
| { | |
| } | |
| protected override bool EqualsCore(PhoneNumber other) | |
| { | |
| return RegionCode == other.RegionCode && | |
| Number == other.Number; | |
| } | |
| protected override int GetHashCodeCore() | |
| { | |
| int hashCode = RegionCode.GetHashCode(); | |
| hashCode = (hashCode * 397) ^ Number.GetHashCode(); | |
| return hashCode; | |
| } | |
| } | |
| public abstract class ValueObject<T> | |
| where T : ValueObject<T> | |
| { | |
| public override bool Equals(object obj) | |
| { | |
| var valueObject = obj as T; | |
| if (ReferenceEquals(valueObject, null)) | |
| return false; | |
| if (GetType() != valueObject.GetType()) | |
| return false; | |
| return EqualsCore(valueObject); | |
| } | |
| public override int GetHashCode() | |
| { | |
| return GetHashCodeCore(); | |
| } | |
| public static bool operator==(ValueObject<T> a, ValueObject<T> b) | |
| { | |
| if (ReferenceEquals(a, null) && ReferenceEquals(b, null)) | |
| return true; | |
| if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) | |
| return false; | |
| return a.Equals(b); | |
| } | |
| public static bool operator!=(ValueObject<T> a, ValueObject<T> b) | |
| { | |
| return !(a == b); | |
| } | |
| protected abstract bool EqualsCore(T other); | |
| protected abstract int GetHashCodeCore(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment