Skip to content

Instantly share code, notes, and snippets.

@martea
Last active November 16, 2017 13:41
Show Gist options
  • Save martea/9e6c63f155c4102555b7a6cea82bd4e6 to your computer and use it in GitHub Desktop.
Save martea/9e6c63f155c4102555b7a6cea82bd4e6 to your computer and use it in GitHub Desktop.
Example of stronly typed enum with class
class MyStronlyTypedEnum
{
public static readonly MyStronlyTypedEnum Good = new MyStronlyTypedEnum(1, "GUUD", "GOOD");
public static readonly MyStronlyTypedEnum Bad = new MyStronlyTypedEnum(2, "BAED", "BAD");
public static readonly MyStronlyTypedEnum Ugly = new MyStronlyTypedEnum(3, "FUGLY", "UGLY");
private MyStronlyTypedEnum(int id, string codeId, string description)
{
Id = id;
CodeId = codeId;
Description = description;
}
public string Description { get; private set; }
public string CodeId { get; private set; }
public int Id { get; private set; }
public static IEnumerable<MyStronlyTypedEnum> All()
{
yield return Good;
yield return Bad;
yield return Ugly;
}
public static explicit operator MyStronlyTypedEnum(int value)
{
var result = All().FirstOrDefault(x => x.Id == value);
if (result != null) return result;
throw new InvalidCastException("The value " + value + " is not a valid " + nameof(MyStronlyTypedEnum));
}
public static explicit operator MyStronlyTypedEnum(string codeId)
{
var result = All().FirstOrDefault(x => x.CodeId == codeId);
if (result != null) return result;
throw new InvalidCastException("The value " + codeId + " is not a valid " + nameof(MyStronlyTypedEnum));
}
public static explicit operator int(MyStronlyTypedEnum o)
{
return o.Id;
}
public static explicit operator string(MyStronlyTypedEnum o)
{
return o.CodeId;
}
}
void Main()
{
MyStronlyTypedEnum.All().Dump("stronly typed enum");
//cast enum to int
var enumObj = MyStronlyTypedEnum.Good;
var enumObjToInt = (int)enumObj;
enumObjToInt.Dump("cast enum to str using explicit operator for int");
//cast enum to int
enumObj = MyStronlyTypedEnum.Bad;
var enumObjTostr = (string)enumObj;
enumObjTostr.Dump("cast enum to str using explicit operator for string");
//cast int to enum
var castToEnum = 1;
var castedToEnum = (MyStronlyTypedEnum)castToEnum;
castedToEnum.Dump("cast string to stornly typed enum using explicit operator");
//cast int to enum
var str = "FUGLY";
castedToEnum = (MyStronlyTypedEnum)str;
castedToEnum.Dump("cast string to stornly typed enum using explicit operator");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment