Skip to content

Instantly share code, notes, and snippets.

@naeemsarfraz
Created August 7, 2016 11:48
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 naeemsarfraz/8b78d8ed228eca21e466fa1f8eb18e0b to your computer and use it in GitHub Desktop.
Save naeemsarfraz/8b78d8ed228eca21e466fa1f8eb18e0b to your computer and use it in GitHub Desktop.
public class Role
{
public static Role Author { get; } = new Role(0, "Author");
public static Role Editor { get; } = new Role(1, "Editor");
public static Role Administrator { get; } = new Role(2, "Administrator");
public static Role SalesRep { get; } = new Role(3, "Sales Representative");
private Role(int val, string name)
{
Value = val;
Name = name;
}
[Obsolete("EntityFramework's best friend", true)]
private Role()
{
// required for EF
}
private int _value;
public int Value
{
get { return _value; }
private set
{
Name = FromValue(value).Name;
_value = value;
}
}
public string Name { get; private set; }
public static IEnumerable<Role> List()
{
return new[] { Author, Editor, Administrator, SalesRep };
}
public static Role FromString(string roleString)
{
return List().FirstOrDefault(r => String.Equals(r.Name, roleString, StringComparison.OrdinalIgnoreCase));
}
public static Role FromValue(int value)
{
return List().FirstOrDefault(r => r.Value == value);
}
protected bool Equals(Role other)
{
return _value == other._value;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Role) obj);
}
public override int GetHashCode()
{
return _value;
}
public static bool operator ==(Role left, Role right)
{
return Equals(left, right);
}
public static bool operator !=(Role left, Role right)
{
return !Equals(left, right);
}
}
@andrewlock
Copy link

One suggestion, I updated the public constructor to set the private backing field _value instead of the property, otherwise I think you will get cyclical dependencies:

    private Role(int val, string name)
    {
        _value = val;
        Name = name;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment