Skip to content

Instantly share code, notes, and snippets.

@hkakutalua
Created April 10, 2018 19:55
Show Gist options
  • Select an option

  • Save hkakutalua/96b0c01f32a8ac7b8fa82d7f19f6a285 to your computer and use it in GitHub Desktop.

Select an option

Save hkakutalua/96b0c01f32a8ac7b8fa82d7f19f6a285 to your computer and use it in GitHub Desktop.
Phone number with equality
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