Create a gist now

Instantly share code, notes, and snippets.

@vkhorikov /1.cs
Last active Dec 2, 2017

What would you like to do?
.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