Skip to content

Instantly share code, notes, and snippets.

@trcio
Last active August 29, 2015 14:04
Show Gist options
  • Save trcio/6b972963f725e7722ebd to your computer and use it in GitHub Desktop.
Save trcio/6b972963f725e7722ebd to your computer and use it in GitHub Desktop.
Provides and Electronic Mail (Email) address.
using System.Text.RegularExpressions;
namespace System.Net.Mail
{
/// <summary>
/// Provides an Electronic Mail (Email) address.
/// </summary>
public sealed class EmailAddress
{
private const string EMAIL_PATTERN = @"([a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*)@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\.+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)";
public string LocalPart { get; private set; }
public string DomainPart { get; private set; }
public string FullAddress { get; private set; }
public EmailAddress() { }
public EmailAddress(string localPart, string domainPart)
{
if (string.IsNullOrWhiteSpace(localPart))
throw new ArgumentNullException("localPart", "localPart is null.");
if (string.IsNullOrWhiteSpace(domainPart))
throw new ArgumentNullException("domainPart", "domainPart is null.");
LocalPart = localPart;
DomainPart = domainPart;
FullAddress = string.Concat(localPart, '@', domainPart);
}
public static bool TryParse(string emailString, out EmailAddress result)
{
try
{
result = Parse(emailString);
return true;
}
catch
{
result = null;
return false;
}
}
public static EmailAddress Parse(string emailString)
{
if (string.IsNullOrWhiteSpace(emailString))
throw new ArgumentNullException("emailString", "emailString is null.");
var match = Regex.Match(emailString, EMAIL_PATTERN);
if (!match.Success) throw new FormatException("emailString is not a valid Email address.");
return new EmailAddress(match.Groups[1].Value, match.Groups[2].Value);
}
public override bool Equals(object obj)
{
if (obj == null) return false;
var other = (EmailAddress) obj;
return FullAddress == other.FullAddress;
}
public override int GetHashCode()
{
return FullAddress.GetHashCode();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment