Click here to Skip to main content
15,883,883 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 35K   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.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 DateTimeInstanceEnum
	{
		/// <summary>
		/// Constructor that must be called to set internal array of values.
		/// </summary>
		public DateTimeInstanceEnum()
		{
            Initialize();
		}

        /// <summary>
        /// Constructor that must be called to set internal array of values.
        /// </summary>
        public DateTimeInstanceEnum(DateTime setValue)
        {
            Initialize();
            this.Value = setValue;
        }
        private void Initialize()
        {
            //check if have _values loaded
            if (_values == null || _values.Length == 0)
            {
                //use reflection to get values
                Type t = this.GetType();
                FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Static);
                _values = new DateTime[fields.Length];
                for (int i = 0; i < fields.Length; i++)
                {
                    if (fields[i].IsInitOnly == true
                        //&& fields[i].IsLiteral == true 
                        && fields[i].FieldType == _value.GetType())
                    {
                        //Need to check if value already loaded
                        DateTime addValue = (DateTime)fields[i].GetValue(null);
                        for (int j = 0; j < _values.Length; j++)
                        {
                            if ((DateTime)_values[j] == addValue)
                            {
                                throw new NotSupportedException("Value with duplicate names not supported.");
                            }
                        }
                        _values[i] = addValue;
                    }
                    if (fields[i].IsInitOnly == true && fields[i].FieldType != _value.GetType())
                    {
                        throw new ArrayTypeMismatchException("A constant with a different type from the value type has been declared. Look for " + fields[i].FieldType.Name);
                    }
                }

            }
        }

		/// <summary>
		/// Using a private array to store values found from reflection
		/// Use the array to check values quickly.
		/// Don't expect a lot of values.
		/// Could possible open up for loading values one time from a database
		/// like Lhotka CLSA read only collection class.
		/// </summary>
		private DateTime[] _values ; 
		
        /// <summary>
		/// Stores assigned value
		/// </summary>
        private DateTime _value ;

        /// <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>
		/// The enum value.
		/// </summary>
		public DateTime Value
		{
            get
            {
                if (_isValueSet == true)
                {
                    return _value;
                }
                else
                {
                    throw new ApplicationException("Value not set");
                }
            }
			set 
			{
                _isValueSet = false;
                //Don't let null in
                //DateTime can't be null.
                //if (value == null)
                //{
                //    throw new NoNullAllowedException("Not allowed to assign null value.");
                //}
                foreach (DateTime v in _values)
                {

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

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

				
			}
		}
		/// <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 DateTime[] GetValues()
		{  //want to return copy
			return (DateTime[])_values.Clone();
		}
		
		/// <summary>
		/// Returns a clone of the available values.
		/// </summary>
		public string[] GetNames()
		{ 	//use reflection to get values
			Type t = this.GetType();
			FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Static );
			string[] names = new string[fields.Length];
			for (int i =0;i<fields.Length ; i++ )
			{
				
				if (fields[i].IsInitOnly == true 
					&& fields[i].IsLiteral == true 
					&& fields[i].FieldType == _value.GetType() )
				{
					names[i] = (string)fields[i].Name ;
				}
				
			}
			return names;
		}
		
		/// <summary>
		/// Two dimensional string array with first dimension as the enum names,
		/// the second dimension containing the enum values converted to string.
		/// </summary>
		/// <returns>two dimensional string array</returns>
		public string[,] GetNamedValues()
		{
			//create two dimensional array
			string[,] namedValues = new string[2,_values.Length];
			Type t = this.GetType();
			FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Static );
			
			for (int i =0;i<fields.Length ; i++ )
			{
				if (fields[i].IsLiteral == true && fields[i].FieldType == _value.GetType() )
				{
					namedValues[0,i] = (string)fields[i].Name ;
					namedValues[1,i] = _values[i].ToString("G");
				}
				
			}
			return namedValues;

		}

		/// <summary>
		/// For the supplied value, returns corresponding Name
		/// Returns zero length string if value not found.
		/// </summary>
		public string GetNameForValue(DateTime forValue)
		{
			
			string name = "";
			
			Type t = this.GetType();
			FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Static );
			
			for (int i =0;i<fields.Length ; i++ )
			{
				if (fields[i].IsInitOnly == true && fields[i].FieldType == _value.GetType() )
				{
					if (forValue == _values[i])
					{
						name =(string)fields[i].Name ;
					}
				}
				
			}


			return name;

		}
		/// <summary>
		/// Returns a DataTable with two columns,
		/// the first for the Name
		/// the second for the Value
		/// </summary>
		public DataTable GetNamedValuesTable()
		{
			//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.DateTime");
			dc.ColumnName = "Value";
			dc.AutoIncrement = false;
			dc.Caption = "Value";
			dc.ReadOnly = true;
			dc.Unique = true;
			dt.Columns.Add(dc);
			
			Type t = this.GetType();
			FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Static );
			
			for (int i =0;i<fields.Length ; i++ )
			{
				
				if (fields[i].IsInitOnly == true && fields[i].FieldType == _value.GetType() )
				{
					dr = dt.NewRow();
					dr["Name"] = (string)fields[i].Name ;
					dr["Value"] = _values[i];
					dt.Rows.Add(dr);
				}
			}
			dt.AcceptChanges();
			return dt;

		}

	} //DateEnum
}

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