Skip to content

Instantly share code, notes, and snippets.

@vkhorikov
Last active December 2, 2017 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkhorikov/1e2ce717f2b0581b5486ecbc290e0263 to your computer and use it in GitHub Desktop.
Save vkhorikov/1e2ce717f2b0581b5486ecbc290e0263 to your computer and use it in GitHub Desktop.
.NET Value Type (struct) as a DDD Value Object
public struct Email
{
public string Value { get; }
public bool IsConfirmed { get; }
public Email(string value, bool isConfirmed)
{
Value = value;
IsConfirmed = isConfirmed;
}
}
Email email1 = new Email("my@email.com", true);
Email email2 = new Email("my@email.com", true);
bool isEqual = email1.Equals(email2); // true
public struct Email : IEquatable<Email>
{
public string Value { get; }
public bool IsConfirmed { get; }
public Email(string value, bool isConfirmed)
{
Value = value;
IsConfirmed = isConfirmed;
}
public bool Equals(Email other)
{
return Value == other.Value && IsConfirmed == other.IsConfirmed;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is Email && Equals((Email)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Value != null ? Value.GetHashCode() : 0) * 397) ^ IsConfirmed.GetHashCode();
}
}
public static bool operator ==(Email a, Email b)
{
return a.Equals(b);
}
public static bool operator !=(Email a, Email b)
{
return !(a == b);
}
}
Email email1 = new Email("my@email.com", true);
Email email2 = new Email("my@email.com", true);
bool isEqual = email1 == email2;
Email email = new Email("my@email.com", true);
Email email = new Email();
Email[] emails = new Email[10];
FormatterServices.GetUninitializedObject(typeof(Customer));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment