Click here to Skip to main content
15,896,153 members
Articles / Programming Languages / C#

Enum Generitized

Rate me:
Please Sign up or sign in to vote.
3.28/5 (10 votes)
12 May 2007CPOL7 min read 35.2K   164   26  
Using Generics to make a different kind of enumeration: easy to comment, and supports many types.
using System;
using System.Reflection;
using System.Collections.Specialized;
using System.Data;

namespace ThreeOaks.EnumGeneritized
{
	/// <summary>
	/// A class to inherit from to create String like enumerations.
	/// Having a public constant for each value will help developers in assigning string values.
	/// </summary>
	[Serializable()]
	public abstract class StringEnumClass
	{
		/// <summary>
		/// Constructor that must be called to set internal array of values.
		/// </summary>
		public StringEnumClass()
		{
            Initialize();
		}

                /// <summary>
        /// Constructor where the value may be set.
        /// </summary>
        /// <param name="setValue">value to set to.</param>
        public StringEnumClass(string setValue)
        {
            Initialize();
            this.Value = setValue;
        }

        /// <summary>
        /// Set internal arrays and dictionaries to hold values.
        /// </summary>
        private void Initialize()
        {
            //get the name of the class
            Type t = this.GetType();

            //check if have _values loaded
            if (_values.Contains(t.FullName) == false)
            {

                //use reflection to get values

                FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Static);
                int numFields = fields.Length;
                string[] values = new string[numFields];
                string[] names = new string[numFields];
                
                Type valueType = Type.GetType("System.String");
                for (int i = 0; i < numFields; i++)
                {
                    if (fields[i].IsInitOnly == true && fields[i].FieldType == valueType) //_value.GetType())
                    {
                        //Need to check if value already loaded
                        string addValue = (string)fields[i].GetValue(null);
                        for (int j = 0; j < values.Length; j++)
                        {
                            if ((string)values[j] == addValue)
                            {
                                throw new NotSupportedException("Value with duplicate names not supported.");
                            } //no dups
                        } //cycle through them
                        values[i] = addValue; //(string)fields[i].GetValue(null) ;
                        names[i] = fields[i].Name;
                    } //get readonly 
                    if (fields[i].IsInitOnly == true && fields[i].FieldType != valueType ) //_value.GetType())
                    {
                        throw new ArrayTypeMismatchException("A constant with a different type from the value type has been declared. Look for " + fields[i].FieldType.Name);
                    } //check for mismatch in data type
                } //loop through Public fields
        
                //values should now be loaded so put in static list
                _values.Add(t.FullName, values);
                _names.Add(t.FullName, names);
            }
        }

        /// <summary>
        /// Using key collection to hold an array by child type.
        /// This way the values only need to load once.
        /// </summary>
        private static HybridDictionary _values = new HybridDictionary();
        /// <summary>
        /// Holds the names of the values per child type.
        /// This way the value names only need to load once.
        /// </summary>
        private static HybridDictionary _names = new HybridDictionary();

        /// <summary>
        /// Holds the current value.
        /// </summary>
        private string _value ; 
		
		/// <summary>
		/// The enum value.
		/// </summary>
		public string Value
		{
            get
            {
                if (_isValueSet == true)
                {
                    return _value;
                }
                else
                {
                    throw new ApplicationException("Value not set");
                }
            }
			set 
			{
                _isValueSet = false;
                //Don't let null in
                if (value == null)
                {
                    throw new NoNullAllowedException("Not allowed to assign null value.");
                }
                
                //get the array to work with from the collection
                string[] values = (string[])_values[this.GetType().FullName];
                foreach (string v in values)
                {

                    if (v == value)
                    {
                        _value = value;

                        _isValueSet = true;
                        return;
                    }
                }
                if (_isValueSet == false)
                {
                    throw new ArgumentOutOfRangeException(value.ToString() + " not found in enumeration.");
                }
			}
		}

        /// <summary>
        /// Holds if value for instance has been set
        /// </summary>
        private bool _isValueSet = false;
        /// <summary>
        /// Indicates if the enum's value has been set.
        /// </summary>
        public bool IsValueSet
        {
            get { return _isValueSet; }
        }
	

		/// <summary>
		/// Returns the name of the assigned value.
		/// </summary>
		public string Name
		{
			get {return GetNameForValue(_value);}
		}

		/// <summary>
		/// Returns a clone of the available values.
		/// </summary>
		public string[] GetValues()
		{  //want to return copy
			string[] values = (string[])_values[this.GetType().FullName];
			return (string[])values.Clone();
		}
		
		/// <summary>
		/// Returns a clone of the available values.
		/// </summary>
		public string[] GetNames()
		{ 	
			string[] names = (string[])_names[this.GetType().FullName];
			return (string[])names.Clone();
			
		}
		
		/// <summary>
		/// Two dimensional string array with first dimension as the "row",
		/// the second dimension containing the "column".
		/// Column 0 is name, Column 1 is the value
		/// </summary>
		/// <returns>two dimensional string array</returns>
		public string[,] GetNamedValues()
		{
			string[] values = (string[])_values[this.GetType().FullName];
			string[] names = (string[])_names[this.GetType().FullName];
			//create two dimensional array
			string[,] namedValues = new string[values.Length,2];
			
			for (int i =0;i<values.Length ; i++ )
			{
					namedValues[i,0] = (string)names[i] ;
					namedValues[i,1] = (string)values[i];
			}


			return namedValues;

		}

		/// <summary>
		/// For the supplied value, returns corresponding Name
		/// Returns zero length string if value not found.
		/// </summary>
		public string GetNameForValue(string forValue)
		{
			
			string[] values = (string[])_values[this.GetType().FullName];
			string[] names = (string[])_names[this.GetType().FullName];
			
			string name = "";
			
			for (int i =0;i<values.Length ; i++ )
			{
				if (forValue == (string)values[i])
				{
					name =(string)names[i] ;
				}
				
				
			}

			return name;

		}
		/// <summary>
		/// Returns a DataTable with two columns,
		/// the first for the Name
		/// the second for the Value
		/// </summary>
		public DataTable GetNamedValuesTable()
		{
			string[] values = (string[])_values[this.GetType().FullName];
			string[] names = (string[])_names[this.GetType().FullName];
			//create table
			DataTable dt = new DataTable();
			DataColumn dc = new DataColumn();
			DataRow dr;
			dc.DataType = System.Type.GetType("System.String");
			dc.ColumnName = "Name";
			dc.AutoIncrement = false;
			dc.Caption = "Name";
			dc.ReadOnly = true;
			dc.Unique = true;
			dt.Columns.Add(dc);

			dc = new DataColumn();
			dc.DataType = System.Type.GetType("System.String");
			dc.ColumnName = "Value";
			dc.AutoIncrement = false;
			dc.Caption = "Value";
			dc.ReadOnly = true;
			dc.Unique = true;
			dt.Columns.Add(dc);
			
			for (int i =0;i<values.Length ; i++ )
			{
				dr = dt.NewRow();
				dr["Name"] = (string)names[i] ;
				dr["Value"] = (string)values[i];
				dt.Rows.Add(dr);
			}
			dt.AcceptChanges();
			return dt;

		}

	} //StringEnumClass

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
United States United States
A biography in this little spot...sure.
I've worked at GTE HawaiianTel. I've worked at Nuclear Plants. I've worked at Abbott Labs. I've consulted to Ameritech Cellular. I've consulted to Zurich North America. I've consulted to International Truck and Engine. Right now, I've consulted to Wachovia Securities to help with various projects. I've been to SHCDirect and now at Cision.

During this time, I've used all kinds of tools of the trade. Keeping it to the more familier tools, I've used VB3 to VB.NET, ASP to ASP/JAVASCRIPT/XML to ASP.NET. Currently, I'm developing with C# and ASP.NET. I built reports in Access, Excel, Crystal Reports, and Business Objects (including the Universes and ETLS). Been a DBA on SQL Server 4.2 to 2000 and a DBA for Oracle. I've built OLTP databases and DataMarts. Heck, I've even done Documentum. I've been lucky to have created software for the single user to thousands of concurrent users.

I consider myself fortunate to have met many different people and worked in many environments. It's through these experiences I've learned the most.

Comments and Discussions