Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Created October 15, 2014 12:48
Show Gist options
  • Save hagbarddenstore/7727894d974683401dfe to your computer and use it in GitHub Desktop.
Save hagbarddenstore/7727894d974683401dfe to your computer and use it in GitHub Desktop.
class Person
{
public Person(string firstname, string lastname)
{
Firstname = firstname;
Lastname = lastname;
}
public string Firstname { get; private set; }
public string Lastname { get; private set; }
public EmailAddress EmailAddress { get; private set; }
public void ChangeEmailAddress(EmailAddress newEmailAddress)
{
if (newEmailAddress == null)
{
throw new ArgumentNullException("newEmailAddress");
}
if (newEmailAddress == EmailAddress)
{
return;
}
EmailAddress = newEmailAddress;
}
}
class EmailAddress
{
public static readonly EmailAddress Empty = new EmailAddress(string.Empty);
private EmailAddress(string emailAddress)
{
Value = emailAddress;
}
public string Value { get; private set; }
public static implicit operator string(EmailAddress emailAddress)
{
return emailAddress.Value;
}
public static implicit operator EmailAddress(string emailAddress)
{
return Parse(emailAddress);
}
public static EmailAddress Parse(string emailAddress)
{
if (!IsValid(emailAddress))
{
throw new FormatException(emailAddress);
}
return new EmailAddress(emailAddress);
}
public static bool TryParse(string emailAddress, out EmailAddress parsedEmailAddress)
{
try
{
parsedEmailAddress = Parse(emailAddress);
return true;
}
catch (FormatException)
{
return false;
}
}
public override string ToString()
{
return Value;
}
private bool IsValid(string emailAddress)
{
if (string.IsNullOrEmpty(emailAddress))
{
return false;
}
return emailAddress.Contains("@");
}
}
/**
* The code above makes this possible:
* var person = new Person("Person", "People");
*
* // Implicit string to email address conversion.
* person.ChangeEmailAddress("person@example.com");
*
* // Using the .ToString() override
* Console.WriteLine(person.EmailAddress);
*
*
* // Implicit email address to string conversion
* string emailAddress = person.EmailAddress;
*
* Console.WriteLine(emailAddress);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment