Created
August 7, 2016 11:48
-
-
Save naeemsarfraz/8b78d8ed228eca21e466fa1f8eb18e0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: