What's wrong with the enums we have now?
As I'm sure everyone reading this will know, enums are simple lightweight types that enable you to define a set of named integral constants. An enum variable can then be set to any one of these constants or (in the case of 'Flags' enums) to a meaningful combination of them.
As such, enums perform a useful role in C# programming. However, they do have a number of shortcomings:
- Their underlying types are always integers (int, long, byte etc). You can't have an enum with an underlying type of double, decimal, string or DateTime for example.
- You can assign any value of the underlying type to an enum variable, whether it corresponds to one of the defined constants or not.
- You can't add methods, properties or other types of member to an enum, though you can add methods to them indirectly using 'extension methods'. See my earlier article (https://www.c-sharpcorner.com/uploadfile/b942f9/how-to-add-methods-to-an-enum-in-C-Sharp/).
- Enum values often have to be cast back to their underlying types, which can be a nuisance in some scenarios - for example when they are used to index a collection.
What can we do about these shortcomings?
In this article, I'd like to demonstrate how we can build a 'generic' enum using C# which:
- Can have any underlying type, except the type of the generic enum itself.
- Can only be assigned values which are actually defined.
- Can have other members apart from the enum constants, though needn't have.
- Has values which never have to be cast back to their underlying type, because they are in fact values of that type already.
All 'ordinary' enums inherit from an abstract class called System.Enum which itself inherits from System.ValueType. Enums are therefore value types themselves.
The System.Enum class contains a number of static methods which can be applied to any enum, such as GetNames, GetValues, IsDefined, Parse and TryParse.
Enums also have some support from the C# language itself which conceals the way they are actually implemented from the programmer. In particular, all enums have a public instance field of their underlying type called 'value_' which contains their current value but is hidden from view except when you use reflection:
using System;
using System.Reflection;
enum Colors
{
Red,
Green,
Blue
}
class Test
{
static void Main()
{
Colors c = Colors.Blue;
Type t = typeof(Colors);
BindingFlags bf = BindingFlags.Instance | BindingFlags.Public;
FieldInfo fi = t.GetField("value__", bf);
int val = (int)fi.GetValue(c);
Console.WriteLine((Colors)val); // Blue
Console.ReadKey();
}
}
Our generic enum will also rely on an abstract class to provide basic functionality and will itself need to be a class (i.e. a reference type), because it's not possible for custom value types to inherit from anything other than System.ValueType or System.Enum.
The abstract base class also needs to be a generic class which takes two type parameters: the type of the 'enum' itself and its underlying type, so that it can use reflection to obtain the names of the constants and their values.
However, the 'Value' property now needs to be explicit because, of course, our generic enum will no longer have any language support. There are also explicit 'Name' and 'Index' properties. The latter records the position of each defined value in the 'names' or 'values' collection and will normally correspond to the order in which they're defined. The only instance field which a generic enum needs and has is the _index field (exposed by the Index property) because the other properties are deducible from this.
As with ordinary enums, it is possible for more than one constant to have the same value. However, combinations of values are not supported.
How is the abstract base class implemented?
The code for the GenericEnum base class is included in the download which accompanies this article but, for the benefit of those who don't like downloading anything from the Internet, here it is 'in the flesh' :-
using System;
using System.Collections.Generic;
using System.Reflection;
public abstract class GenericEnum<T, U> where T : GenericEnum<T, U>, new()
{
static readonly List<string> names;
static readonly List<U> values;
static bool allowInstanceExceptions;
static GenericEnum()
{
Type t = typeof(T);
Type u = typeof(U);
if (t == u) throw new InvalidOperationException(String.Format("{0} and its underlying type cannot be the same", t.Name));
BindingFlags bf = BindingFlags.Static | BindingFlags.Public;
FieldInfo[] fia = t.GetFields(bf);
names = new List<string>();
values = new List<U>();
for (int i = 0; i < fia.Length; i++)
{
if (fia[i].FieldType == u && (fia[i].IsLiteral || fia[i].IsInitOnly))
{
names.Add(fia[i].Name);
values.Add((U)fia[i].GetValue(null));
}
}
if (names.Count == 0) throw new InvalidOperationException(String.Format("{0} has no suitable fields", t.Name));
}
public static bool AllowInstanceExceptions
{
get { return allowInstanceExceptions; }
set { allowInstanceExceptions = value; }
}
public static string[] GetNames()
{
return names.ToArray();
}
public static string[] GetNames(U value)
{
List<string> nameList = new List<string>();
for (int i = 0; i < values.Count; i++)
{
if (values[i].Equals(value)) nameList.Add(names[i]);
}
return nameList.ToArray();
}
public static U[] GetValues()
{
return values.ToArray();
}
public static int[] GetIndices(U value)
{
List<int> indexList = new List<int>();
for (int i = 0; i < values.Count; i++)
{
if (values[i].Equals(value)) indexList.Add(i);
}
return indexList.ToArray();
}
public static int IndexOf(string name)
{
return names.IndexOf(name);
}
public static U ValueOf(string name)
{
int index = names.IndexOf(name);
if (index >= 0)
{
return values[index];
}
throw new ArgumentException(String.Format("'{0}' is not a defined name of {1}", name, typeof(T).Name));
}
public static string FirstNameWith(U value)
{
int index = values.IndexOf(value);
if (index >= 0)
{
return names[index];
}
throw new ArgumentException(String.Format("'{0}' is not a defined value of {1}", value, typeof(T).Name));
}
public static int FirstIndexWith(U value)
{
int index = values.IndexOf(value);
if (index >= 0)
{
return index;
}
throw new ArgumentException(String.Format("'{0}' is not a defined value of {1}", value, typeof(T).Name));
}
public static string NameAt(int index)
{
if (index >= 0 && index < Count)
{
return names[index];
}
throw new IndexOutOfRangeException(String.Format("Index must be between 0 and {0}", Count - 1));
}
public static U ValueAt(int index)
{
if (index >= 0 && index < Count)
{
return values[index];
}
throw new IndexOutOfRangeException(String.Format("Index must be between 0 and {0}", Count - 1));
}
public static Type UnderlyingType
{
get { return typeof(U); }
}
public static int Count
{
get { return names.Count; }
}
public static bool IsDefinedName(string name)
{
if (names.IndexOf(name) >= 0) return true;
return false;
}
public static bool IsDefinedValue(U value)
{
if (values.IndexOf(value) >= 0) return true;
return false;
}
public static bool IsDefinedIndex(int index)
{
if (index >= 0 && index < Count) return true;
return false;
}
public static T ByName(string name)
{
if (!IsDefinedName(name))
{
if (allowInstanceExceptions) throw new ArgumentException(String.Format("'{0}' is not a defined name of {1}", name, typeof(T).Name));
return null;
}
T t = new T();
t._index = names.IndexOf(name);
return t;
}
public static T ByValue(U value)
{
if (!IsDefinedValue(value))
{
if (allowInstanceExceptions) throw new ArgumentException(String.Format("'{0}' is not a defined value of {1}", value, typeof(T).Name));
return null;
}
T t = new T();
t._index = values.IndexOf(value);
return t;
}
public static T ByIndex(int index)
{
if (index < 0 || index >= Count)
{
if (allowInstanceExceptions) throw new ArgumentException(String.Format("Index must be between 0 and {0}", Count - 1));
return null;
}
T t = new T();
t._index = index;
return t;
}
protected int _index;
public int Index
{
get { return _index; }
set
{
if (value < 0 || value >= Count)
{
if (allowInstanceExceptions) throw new ArgumentException(String.Format("Index must be between 0 and {0}", Count - 1));
return;
}
_index = value;
}
}
public string Name
{
get { return names[_index]; }
set
{
int index = names.IndexOf(value);
if (index == -1)
{
if (allowInstanceExceptions) throw new ArgumentException(String.Format("'{0}' is not a defined name of {1}", value, typeof(T).Name));
return;
}
_index = index;
}
}
public U Value
{
get { return values[_index]; }
set
{
int index = values.IndexOf(value);
if (index == -1)
{
if (allowInstanceExceptions) throw new ArgumentException(String.Format("'{0}' is not a defined value of {1}", value, typeof(T).Name));
return;
}
_index = index;
}
}
public override string ToString()
{
return names[_index];
}
}
Anandu G NathPosted Jan 6, 2024, 10:13 AM
Informative
Upendra Pratap ShahiPosted Jun 24, 2015, 7:27 AM
nice article sir..
Ken HPosted Mar 26, 2015, 5:01 AM
Nice article, thank :)
Vithal WadjePosted Mar 23, 2015, 1:40 PM
very happy to see Vulpes sir article
Tom MohanPosted Mar 23, 2015, 4:48 AM
Great effort
Suthish NairPosted Oct 11, 2011, 3:29 AM
Can we create dynamic Enums?