sarpay
7/31/2018 - 9:16 AM

ENum

Includes Enum formatting.

public enum TriStateBoolean 
{
  [EnumMember(Value = "PRT")]
  PRT,
  [EnumMember(Value = "XYZ")]
  XYZ,
  [EnumMember(Value = "MKA")]
  MKA
};
// Summary:
//  Returns an indication whether a constant with a specified value exists in
//  a specified enumeration.

// Returns:
//  true if a constant in enumType has a value equal to value; otherwise, false.

if (System.Enum.IsDefined(typeof(OperationTypeEnum), 1))
{
  // Do something
}

HELPER METHODS

public static List<KeyValuePair<TEnum, string>> ToEnumDescriptionsList<TEnum>(this TEnum value)
{
  return Enum
        .GetValues(typeof(TEnum))
        .Cast<TEnum>()
        .Select(x => new KeyValuePair<TEnum, string>(x, ((Enum)((object)x)).GetDescription()))
        .ToList();
}

Perform LINQ on Enums

public enum PolicyNoteTypeEnum : byte
{
  [Description("Sertifika")] Certificate = 1,
  [Description("Bilgi Bekleniyor(TUW)")] WaitingInformationTUW = 2,
  [Description("Bilgi Bekleniyor(MUW)")] WaitingInformationMUW = 3,
  [Description("Acente")] Agency = 4,
  [Description("Poliçe")] Policy = 5,
  [Description("Kullanıcı")] User = 6,
  [Description("Sistem")] System = 7,
  [Description("Görüş")] Review = 8,
  [Description("Yenileme")] Renewal = 9
}

var enumNamesList = (from enumval in Enum.GetValues(typeof(PolicyNoteTypeEnum)).Cast<PolicyNoteTypeEnum>().ToList() 
                     where enumval != PolicyNoteTypeEnum.Review 
                     select Enum.GetName(typeof(PolicyNoteTypeEnum), enumval)).ToList();

// >>> Get description from a given enum object
private static string NoteTypeTitleTagText(HinsuraEnums.PolicyNoteTypeEnum noteType)
{
  return default(HinsuraEnums.PolicyNoteTypeEnum).ToEnumDescriptionsList().First(p => p.Key == noteType).Value;
}

Get Description Text From Property Name in String

public enum EarnedRightsTypeEnum
{
  [Description("Yenileme Garantisi")]
  YG,
  [Description("Ömür Boyu Yenileme Garantisi")]
  OBYG
}

Enum.TryParse("YG", out EarnedRightsTypeEnum earnedRightsTypeEnum);
var earnedRightsTypeDescTxt = Extensions.GetDescription(earnedRightsTypeEnum);

// output: "Yenileme Garantisi"

Enum to SelectList

public enum GenderEnum
{
  [Description("Erkek")]
  Man = 'E',
  [Description("Kadın")]
  Woman = 'K',
  [Description("Diğer")]
  Other = 'D'
}

ViewData["Gender"] = default(GenderEnum).ToEnumDescriptionsList()
                      .Select(
                        p =>
                          new SelectListItem {Value = p.Key.ToString(), Text = p.Value}
                      );

SAMPLE

public enum EndorsementTypeEnum : byte
{
  [Description("Sigorta Ettiren Değişikliği")]
  PolicyHolder = 1,
  [Description("Lehdar Değişikliği")]
  Beneficiary = 2,
  [Description("Kazanılmış Hak tarihi Değişikliği")]
  EarnedRightsDate = 3,
  [Description("Sigortalı Yakınlık Türü")]
  InsuredType = 4
}

Get the name of an enum

string insuredType = Enum.GetName(typeof(EndorsementTypeEnum), EndorsementTypeEnum.InsuredType);
// outputs: insuredType = "InsuredType"

Convert enum to a string array of names

string[] names = Enum.GetNames(typeof(Languages));

Convert enum to a list of enum types and filter / search

var enumToList = Enum.GetValues(typeof(EndorsementTypeEnum)).Cast<EndorsementTypeEnum>().ToList();
var cancellationEndorsementTypesList = enumToList.Where(
  x => x == EndorsementTypeEnum.RemovePersonFromCollectingIssue
);

convert enum to an array of enum types and filter / search

EndorsementTypeEnum[] result = (EndorsementTypeEnum[])Enum.GetValues(typeof(EndorsementTypeEnum))

Get description from value

using System.ComponentModel;
using System.Reflection;

namespace Project.API.Models.Extensions;

public static class EnumExtensions
{
    public static string GetEnumDescription(Enum eEnum)
    {  
        var enumMember = eEnum.GetType().GetMember(eEnum.ToString()).FirstOrDefault();
            
        var descriptionAttribute =
            enumMember == null
                ? default
                : enumMember.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
            
        return
            descriptionAttribute == null
                ? eEnum.ToString()
                : descriptionAttribute.Description;
    }
}

// USAGE
var notificationTypeDescription =
  EnumExtensions.GetEnumDescription((NotificationTypeEnum) notificationDto.NotificationTypeId.GetValueOrDefault());

SAMPLE

public enum GroupDiscountWorkingTypeEnum : byte
{
  ApplyDirect = 0,
  ApplyInList = 1,
  AgencyOwner = 2
}

var groupDiscount = await _productManager.GetGroupDiscountFirstOrDefault(groupDiscountViewModel.Id);
if (groupDiscount.WorkingType.ToString("G") == "ApplyDirect") {
  /**/
}

SAMPLE

public enum LookUpKeyEnum
{
  [Description("UserAuthProfile")] UserAuthProfile,
  [Description("AuthTarget")] AuthTarget,
  [Description("AuthType")] AuthType
}

Cast String to ENum

// Alt. 1
LookUpKeyEnum key = (LookUpKeyEnum)Enum.Parse(typeof(LookUpKeyEnum), "AuthType");

// Alt. 2
var lookupKeyEnumStr = "AuthType";
LookUpKeyEnum key = lookupKeyEnumStr.ToPascalCase().ToEnum<LookUpKeyEnum>();

// Alt. 3
public enum EarnedRightsTypeEnum
{
  [Description("Yenileme Garantisi")]
  YG,
  [Description("Ömür Boyu Yenileme Garantisi")]
  OBYG
}
Enum.TryParse("OBYG", out EarnedRightsTypeEnum earnedRightsTypeEnum);
// output: Ömür Boyu Yenileme Garantisi

Cast Int to ENum

YourEnum foo = (YourEnum)yourInt;

// -- or --

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);

ENum to string

string key = Enum.GetName(typeof(LookUpKeyEnum), LookUpKeyEnum.AuthType);

Enum to List

List<KeyValuePair<LookUpKeyEnum, string>> list = 
      default(LookUpKeyEnum).ToEnumDescriptionsList();

Enum to SelectList

IEnumerable<SelectListItem> lookupKeysList = 
    EnumHelper<LookUpKeyEnum>.GetSelectList().OrderBy("Text");
    
ViewBag.LookUpKeys = new SelectList(lookupKeysList, "Value", "Text", modelView.LookupKey);

SAMPLE

public GroupDiscountWorkingTypeEnum WorkingType { get; set; }

public enum GroupDiscountWorkingTypeEnum : byte
{
  ApplyDirect = 0,
  ApplyInList = 1,
  AgencyOwner = 2
}

<div class="col-md-3">
  @Html.EditorFor(
    model => model.GroupDiscountId, 
    new { groupDiscountWorkingType = GroupDiscountWorkingTypeEnum.ApplyInList, isRequired = false }
  )
</div>

List<GroupDiscount> resultList;
if (ViewData["groupDiscountWorkingType"] != null)
{
  resultList = productManager.GetAllGroupDiscountsList().Result.OrderBy(r => r.Id)
    .Where(
        x => x.WorkingType == (GroupDiscountWorkingTypeEnum) ViewData["groupDiscountWorkingType"]
    ).ToList();
}

SAMPLE

public enum DocumentSystemTypeEnum
{
    [Description("Hinsura")] Hinsura = 1,
    [Description("IBM File Net")] FileNet = 2,
    [Description("Internal")] Internal = 3,
    [Description("Share Pint")] SharePoint = 4
}

var documentSystemType = (DocumentSystemTypeEnum)int.Parse("2");
if (documentSystemType == DocumentSystemTypeEnum.Hinsura)
{
  /* false */
}

SAMPLE

public enum Color : byte {Red = 1, Blue = 2, Green = 3};
Color myColor = Color.Green;


byte something = (byte)Color.Red;
//  something = 1


Console.WriteLine("The value of myColor is {0}.", myColor.ToString("G"));.
//  The value of myColor is Green.

Console.WriteLine("The value of myColor is {0}.", myColor.ToString("F"));
//  The value of myColor is Green.

Console.WriteLine("The value of myColor is {0}.", myColor.ToString("D"));
//  The value of myColor is 3.

Console.WriteLine("The value of myColor is 0x{0}.", myColor.ToString("X"));
//  The value of myColor is 0x00000003.

G or g
Displays the enumeration entry as a string value, if possible, and otherwise displays the integer value of the current instance. If the enumeration is defined with the Flags attribute set, the string values of each valid entry are concatenated together, separated by commas. If the Flags attribute is not set, an invalid value is displayed as a numeric entry.

F or f Displays the enumeration entry as a string value, if possible. If the value can be completely displayed as a summation of the entries in the enumeration (even if the Flags attribute is not present), the string values of each valid entry are concatenated together, separated by commas. If the value cannot be completely determined by the enumeration entries, then the value is formatted as the integer value.

D or d Displays the enumeration entry as an integer value in the shortest representation possible. The following example illustrates the D format specifier.

X or x Displays the enumeration entry as a hexadecimal value. The value is represented with leading zeros as necessary, to ensure that the value is a minimum eight digits in length. The following example illustrates the X format specifier.

//String Enumerations

//Constants

//The constants can be easily accessed as MyConsts.Val1 etc. This is extremely simple and 
//reasonably neat. As these are constants the values are compiled in and as such can also 
//be used nicely in switch statements.

//Constants do have an interesting side effect in that the values are actually copied to any 
//client code that uses the class. This means that client assemblies could potentially have 
//out of date values if the values in the constants assembly were to change and it were redeployed 
//without a client rebuild.

public static class MaritalStatus
{
  public const string E = "Evli";
  public const string B = "Bekar";
  public const string D = "Diğer";

}


//Static readonly

//readonly values can be initialized with a value and changed only within a class's constructor. 
//This effectively means their eventual value is not known at compile time. The code sample above 
//can be changed slightly to illustrate this 'pseudo const'.

public static class MaritalStatus
{
  public static readonly string E = "Evli";
  public static readonly string B = "Bekar";
  public static readonly string D = "Diğer";
}

// USAGE

switch (insured.MaritalStatus)
{
  case "E": maritalStatus = MaritalStatus.E; break;
  case "B": maritalStatus = MaritalStatus.B; break;
  case "D": maritalStatus = MaritalStatus.D; break;
}