[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 749
  • Last Modified:

Get value of enumeration as string

hi,

i have enumeration as:

     public enum myenum
        {
            Type = SqlDbType.NVarChar
        }

and in any other method i need when calling this enum get the string as : SqlDbType.NVarChar
 string ss = myenum.Type.tostring();

this should result : SqlDbType.NVarChar

but i am getting the result as "Type"

any ideas??

thanks




0
Abu Hamdan
Asked:
Abu Hamdan
  • 2
1 Solution
 
tiagosalgadoCommented:
You can do what you want in that simple way. To create an enum and return a string value, you can do something like this
// Create a class to read the attribut that you set on Enum options.
public class StringValueAttribute : System.Attribute
    {
 
        private string _value;
 
        public StringValueAttribute(string value)
        {
            _value = value;
        }
 
        public string Value
        {
            get { return _value; }
        }
 
    }
 
And on your Enum you can have this:
 
public enum myenum
        {
            [StringValue("SqlDbType.NVarChar")]
            Type = SqlDbType.NVarChar
        }

Open in new window

0
 
tiagosalgadoCommented:
Sorry, don't know why not my all code pasted. After the enum add this too.
 

private static Hashtable _stringValues = new Hashtable();
        public static string GetStringValue(Enum value)
        {
            string output = null;
            Type type = value.GetType();
 
            //Check first in our cached results...
            if (_stringValues.ContainsKey(value))
                output = (_stringValues[value] as StringValueAttribute).Value;
            else
            {
                //Look for our 'StringValueAttribute' 
                //in the field's custom attributes
                FieldInfo fi = type.GetField(value.ToString());
                StringValueAttribute[] attrs =
                   fi.GetCustomAttributes(typeof(StringValueAttribute),
                                           false) as StringValueAttribute[];
                if (attrs.Length > 0)
                {
                    _stringValues.Add(value, attrs[0]);
                    output = attrs[0].Value;
                }
            }
 
            return output;
        }

Open in new window

0
 
Abu HamdanEnterprise Architect, PM ExpertAuthor Commented:
thanks
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now