In the process of porting some code from an existing Java application to C#, I came across the following enum:
public enum UnitType
{
APT("Apartment"),
BOX("Box"),
LOT("Lot"),
PIER("Pier"),
RM("Room"),
RR("Rural Route"),
SLIP("Slip"),
ST("Street"),
STE("Suite"),
UNIT("Unit"),
WHARF("Wharf"),
WING("Wing");
private String label;
UnitType(String label)
{
this.label = label;
}
public String getLabel()
{
return label;
}
}
That's all well and good, but .NET enums are not full-blown objects as they are in Java. Since I really just need key-value associations in this case, a Dictionary would fit the bill here. But what about the calling code? It would be nice not to muddy things up with extraneous explicit trips to said dictionary. Let's apply some extension method magic…
public enum UnitType
{
APT, BOX, LOT, PIER, RM, RR, SLIP, ST, STE, UNIT, WHARF, WING
}
public static class UnitTypeExtensions
{
public static String GetLabel(this UnitType enumValue)
{
return UnitTypeLabels[key: enumValue];
}
private static IDictionary<UnitType, string> UnitTypeLabels =
new Dictionary<UnitType, string>
{
{ UnitType.APT , "Apartment" },
{ UnitType.BOX , "Box" },
{ UnitType.LOT , "Lot" },
{ UnitType.PIER , "Pier" },
{ UnitType.RM , "Room" },
{ UnitType.RR , "Rural Route" },
{ UnitType.SLIP , "Slip" },
{ UnitType.ST , "Street" },
{ UnitType.STE , "Suite" },
{ UnitType.UNIT , "Unit" },
{ UnitType.WHARF, "Wharf" },
{ UnitType.WING , "Wing" }
};
}
Perfect. Without adding too much code, requesting mapped labels is now a part of UnitType's API:
string label = UnitType.APT.GetLabel(); // label value is "Apartment"