Login using System.Noticeably.Different.WebSite;
March 10, 2010 NoticeablyDifferent
Search for
 
C# 2.0 String restricted by Regular Expression Class 
[Serializable]
public abstract class RegExRestrictedString : IEquatable<RegExRestrictedString> {
    string internalValue;
 
    public RegExRestrictedString() { }
 
    public virtual RegexOptions Options {
        get { return RegexOptions.None; }
    }
 
    protected abstract string Pattern { get; }
 
    public string Value {
        get { return internalValue; }
        set {
            Validate(value);
            this.internalValue = value;
        }
    }
 
    private void Validate(string value) {
        if (string.IsNullOrEmpty(Pattern)) throw new InvalidOperationException(
            "Pattern cannot be null or empty when assigning value.");
        Regex regEx = new Regex(Pattern, Options);
        if (regEx.Matches(value).Count != 1) 
            throw new InvalidOperationException("Value does not match given restriction.");
    }
 
    public override string ToString() {
        return internalValue;
    }
 
    public override bool Equals(object obj) {
        return (obj is RegExRestrictedString) && Equals((RegExRestrictedString)obj);
    }
 
    public override int GetHashCode() {
        return internalValue.GetHashCode()^Pattern.GetHashCode()^Options.GetHashCode();
    }
 
    public bool Equals(RegExRestrictedString other) {
        if (object.ReferenceEquals(other, null)) return false;
        return ((Pattern == other.Pattern) && (Value == other.Value)
            && (Options == other.Options));
    }
 
    public static bool operator ==(RegExRestrictedString first, RegExRestrictedString second) {
        if (object.ReferenceEquals(first, second)) return true;
        if (object.ReferenceEquals(first, null) || object.ReferenceEquals(second, null))
            return false;
        return ((first.Pattern == second.Pattern) && (first.Value == second.Value)
            && (first.Options == second.Options));
    }
 
    public static bool operator !=(RegExRestrictedString first, RegExRestrictedString second) {
        return !first.Equals(second);
    }
}
 
 
Sample usage:
 
public class Comment : RegExRestrictedString {
 
    public Comment() { }
 
    public static implicit operator Comment(string value) {
        return new Comment().Value = value;
    }
 
    protected override string Pattern {
        get { return "[a-zA-Z \t\n\r\f\v]{0,40}"; }
    }
}