CodeXchange Friday, March 29, 2024
Home
What's it?
Download
Register
My Snippets
Add Snippet
Search
Faq
Contact Us
Sponsors

Website hosted by


Code Snippet Preview

Review the code snippet before inserting it on your project.

Snippet Metadata
Summary: Allows you to add string values to Enumerations using an Attribute.
Language: C#
Author: John Tolar
Author snippets RSS:
Culture: en-US
Bytes: 9864
Visual Studio 2005 Snippet:

Snippet Stats
Downloads: 1
Overall rating : 0
Average rating : Snippet rating

Snippet Preview
Code:
/* EXAMPLE OF Implementation.
[Flags]
    public enum DaysOfTheWeek : short
    {
        [StringValue("Sunday")]
        Sunday = 1,
        [StringValue("Monday")]
        Monday = 2,
        [StringValue("Tuesday")]
        Tuesday = 4,
        [StringValue("Wednesday")]
        Wednesday = 8,
        [StringValue("Thursday")]
        Thursday = 16,
        [StringValue("Friday")]
        Friday = 32,
        [StringValue("Saturday")]
        Saturday = 64,
        [StringValue("AllDays")]
        AllDays = Saturday | Friday | Thursday | Wednesday | Tuesday | Monday | Sunday,
    }
*/
#region Class StringEnum
    /// 
    /// Helper class for working with 'extended' enums using  attributes.
    /// 
    public class StringEnum
    {
        #region Instance implementation
        private static readonly Hashtable StringValues = new Hashtable();
        private readonly Type _enumType;
        /// 
        /// Creates a new  instance.
        /// 
        /// Enum type.
        public StringEnum(Type enumType)
        {
            if (!enumType.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", enumType));
            _enumType = enumType;
        }
        /// 
        /// Gets the underlying enum type for this instance.
        /// 
        /// 
        public Type EnumType
        {
            get { return _enumType; }
        }
        /// 
        /// Gets the string value associated with the given enum value.
        /// 
        /// Name of the enum value.
        /// String Value
        public string GetStringValue(string valueName)
        {
            string stringValue = null;
            try
            {
                var enumType = (Enum) Enum.Parse(_enumType, valueName);
                stringValue = GetStringValue(enumType);
            }
            catch
            {
                //Swallow!
            } 
            return stringValue;
        }
        /// 
        /// Gets the string values associated with the enum.
        /// 
        /// String value array
        public Array GetStringValues()
        {
            var values = new ArrayList();
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs != null)
                    if (attrs.Length > 0)
                        values.Add(attrs[0].Value);
            }
            return values.ToArray();
        }
        /// 
        /// Gets the values as a 'bindable' list datasource.
        /// 
        /// IList for data binding
        public IList GetListValues()
        {
            Type underlyingType = Enum.GetUnderlyingType(_enumType);
            var values = new ArrayList();
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs != null)
                    if (attrs.Length > 0)
                        values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType),
                                                       attrs[0].Value));
            }
            return values;
        }
        /// 
        /// Return the existence of the given string value within the enum.
        /// 
        /// String value.
        /// Existence of the string value
        public bool IsStringDefined(string stringValue)
        {
            return Parse(_enumType, stringValue) != null;
        }
        /// 
        /// Return the existence of the given string value within the enum.
        /// 
        /// String value.
        /// Denotes whether to conduct a case-insensitive match on the supplied string value
        /// Existence of the string value
        public bool IsStringDefined(string stringValue, bool ignoreCase)
        {
            return Parse(_enumType, stringValue, ignoreCase) != null;
        }
        #endregion
        #region Static implementation
        /// 
        /// Gets a string value for a particular enum value.
        /// 
        /// Value.
        /// String Value associated via a  attribute, or null if not found.
        public static string GetStringValue(Enum value)
        {
            string output = null;
            Type type = value.GetType();
            if (StringValues.ContainsKey(value))
                output = ((StringValueAttribute) StringValues[value]).Value;
            else
            {
                //Look for our 'StringValueAttribute' in the field's custom attributes
                FieldInfo fi = type.GetField(value.ToString());
                var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs != null)
                    if (attrs.Length > 0)
                    {
                        StringValues.Add(value, attrs[0]);
                        output = attrs[0].Value;
                    }
            }
            return output;
        }
        /// 
        /// Parses the supplied enum and string value to find an associated enum value (case sensitive).
        /// 
        /// Type.
        /// String value.
        /// Enum value associated with the string value, or null if not found.
        public static object Parse(Type type, string stringValue)
        {
            return Parse(type, stringValue, false);
        }
        /// 
        /// Parses the supplied enum and string value to find an associated enum value.
        /// 
        /// Type.
        /// String value.
        /// Denotes whether to conduct a case-insensitive match on the supplied string value
        /// Enum value associated with the string value, or null if not found.
        public static object Parse(Type type, string stringValue, bool ignoreCase)
        {
            object output = null;
            string enumStringValue = null;
            if (!type.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", type));
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in type.GetFields())
            {
                //Check for our custom attribute
                var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs != null)
                    if (attrs.Length > 0)
                        enumStringValue = attrs[0].Value;
                //Check for equality then select actual enum value.
                if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
                {
                    output = Enum.Parse(type, fi.Name);
                    break;
                }
            }
            return output;
        }
        /// 
        /// Return the existence of the given string value within the enum.
        /// 
        /// String value.
        /// Type of enum
        /// Existence of the string value
        public static bool IsStringDefined(Type enumType, string stringValue)
        {
            return Parse(enumType, stringValue) != null;
        }
        /// 
        /// Return the existence of the given string value within the enum.
        /// 
        /// String value.
        /// Type of enum
        /// Denotes whether to conduct a case-insensitive match on the supplied string value
        /// Existence of the string value
        public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
        {
            return Parse(enumType, stringValue, ignoreCase) != null;
        }
        #endregion
    }
    #endregion
    #region Class StringValueAttribute
    /// 
    /// Simple attribute class for storing String Values
    /// 
    public class StringValueAttribute : Attribute
    {
        private readonly string _value;
        /// 
        /// Creates a new  instance.
        /// 
        /// Value.
        public StringValueAttribute(string value)
        {
            _value = value;
        }
        /// 
        /// Gets the value.
        /// 
        /// 
        public string Value
        {
            get { return _value; }
        }
    }
    #endregion

Snippet Comments
Comments:
No comments for this snippet

Other snippets that may interest you..
Related Snippets
TDT - GridPage - Page_Init (C#)
CustomValitaor (C#)
(C#)
Get the file extension from a file path or file name (VB.NET)
grab record from db and subtracts it from variable (VB.NET)



Copyright ©2009-2024 CodeXchange. Server version 1.0.3720.32855 Client Version 0.9.0.0

With from Barcelona

Most Helpful members
These are the members who have received the most points for their helpful samples
Zepho Zep
Robert Wagner
Galen Taylor

All time 'Hall of fame'
Formating a file size and adding the B, KB, MB and GB extension appropriately with string.Format (C#)
INI File Access (VB.NET)
Read XML from string into DataSet (C#)
Create Manifest File for your Application (VB.NET)
Round function to avoid banker's rounding (VB.NET)
Get Short and Long Path Names (VB.NET)
Sending Mail through authenticated SMTP server (C#)
One Way Hash for strings (C#)
Formating a file size and adding the B, KB, MB and GB extension appropriately with string.Format (C#)
How do I load an image from a URI address? (VB.NET)
Use our easy to use Visual Studio.NET addin client and start sharing code snippets with the CodeXchange community!
Refreshed: Friday, March 29, 2024