Blog

Filter posts by the Tags of Blog section!

Setting title for enum members and getting them through an extension method Sunday, 19 July 2015

Assume the following enum: 



  

  public enum SettingKey

    {

        APIVersion = 1,

        IOSVersion = 2,

    }


 

We can set a title or description or any other property for the members of the enum and get them. Take a look at the following class derived from the Attribute class:

 


 

public class SettingKeyAttribute : Attribute

    {

        public string Title { get; private set; }



        public string Description { get; private set; }





        public SettingKeyAttribute(string title, string description)

        {

            Title = title;

            Description = description;

        }

    }


 

I want to give the members title and descriptions and get them with an extension method: 

 

public static class MyExtensions

    {

        public static string GetSettingTitle<TEnum>(this TEnum value)

        {

            if (typeof(TEnum) == typeof(SettingKey))

                return ((SettingKeyAttribute)(typeof(TEnum)).GetMember(value.ToString()).FirstOrDefault().GetCustomAttributes(typeof(SettingKeyAttribute), false).FirstOrDefault()).Title;

            return string.Empty;

        }

    }


 

By modifying the enum like this: 


  

  public enum SettingKey

    {

        [SettingKey("APIVersion", "This is the description section")]

        APIVersion = 1,

       

        [SettingKey("IOSVersion", "")]

        IOSVersion = 2,

    }


 

There could be lots of usages for such a helper. For example when you want to add the enum members as a key in the database with a title or description or anything else based on your needs. Take a look at my scenario:


 

  public class Setting

    {

        public string KeyTitle { get; set; }



        public string Description { get; set; }



        public SettingKey Key { get; set; }



        public string Value { get; set; }



    }



 

In a case that I need Add Title and Description for the defined Key: 



 

  var settingKeys = GeneralUtility.GetEnumMembers<SettingKey>().Select(member => new Setting

                {

                    KeyTitle = member.GetSettingTitle(),

                    CreateDate = DateTime.Now,

                    Key = member,

                    IsEncrypted = member.GetSettingEncrypt()



                }).ToList();


 

That’s it! The GeneralUtiliti that I used in the above code: 


 

public static class GeneralUtility

{

     

        public static List<TEnum> GetEnumMembers<TEnum>()

        {

            return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToList();

        }

}


 

Hope it helps!

Tags: C#

comments powered by Disqus