Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / C#

A Class Based Enumeration Implementation

Rate me:
Please Sign up or sign in to vote.
3.89/5 (8 votes)
28 Jan 2013LGPL32 min read 37.3K   25   8
A classical implementation of the enumeration using class together with NHibernate user types

Introduction

The ClassEnum library is a class-based implementation of enumeration for scenarios where language enum cannot do the job.

Why to Use ClassEnum

C# enum is very convenient, but it can only have one string name without any space and special character in it.

One simple example to show why we need a class implemented could be a credit card type. There are 4 common credit card types: Visa, Master, American Express and Discover Card. If you use C# enum to represent these types, you will have to use AmericanExpress and DiscoverCard as the enum name, which could be cumbersome when you try to display them.
A class based enumeration implementation is simple. It uses static readonly fields of a class as enumeration items, and declares the constructor to be private to make it safe. Here is an example of a class based enumeration for credit card types:

C#
public sealed class CreditCardType {
    public static readonly CreditCardType AmericanExpress =
            new CreditCardType("American Express");
    public static readonly CreditCardType DiscoverCard =
            new CreditCardType("Discover Card");
    public static readonly CreditCardType Master = new CreditCardType("Master");
    public static readonly CreditCardType Visa = new CreditCardType("Visa");
    private readonly string name;
    private CreditCardType(string name) {

        this.name = name;
    }
    public override string ToString() {

        return name;
    }
}

The power of this class based implementation is that you can add properties or even functions if needed. Something missing here is the Enum.Parse function which allows you to parse an enum type from a string. Also this class based enumeration needs to be able to be mapped in NHibernate. ClassEnum library offers a base class for creating such class based enumeration with some basic functions such as Parse and a NHiberante User type.

ClassEnum is easy to use. You create your own class based enumeration by inheriting the ClassEnumGeneric<T> abstract class. T here is the type of your class based enumeration.

C#
public class CreditCardType : ClassEnumGeneric<CreditCardType>
{
    public readonly  static CreditCardType Visa = new CreditCardType("Visa");
    public readonly  static CreditCardType AmericanExpress = new CreditCardType("American Express");
    private CreditCardType(string name):base(name) {}

}

Now this CreditCardType automatically inherits the useful functions and properties from ClassEnumGeneric:

C#
// static parse function
CreditCardType.Parse("Visa"); //returns CreditCardType.Visa
 
// static Items property that returns a collection that contains
// CredictCardType.Visa and CredictCardType.AmericanExpress
// and other CredictCardTypesif declared.
CreditCardType.Items; //returns a collection that contains

ClassEnum implementation can be more powerful as you can use inheritance and polymorphisms in the class-based implementation. Here is an example:

C#
public class CreditCardType : ClassEnumGeneric<CreditCardType> {
      public readonly static CreditCardType Visa = new Visa();
      public readonly static CreditCardType AmericanExpress = new AmericanExpress();
      protected CreditCardType(string name) : base(name) {}

      public abstract bool ValidateCCNumber(string ccNumber);

      private class Visa : CreditCardType {

          public Visa() : base("Visa") {}
          public override bool ValidateCCNumber(string ccNumber){

            //....do some Visa validation
          }
      }

      private class AmericanExpress : CreditCardType {

          public AmericanExpress() : base("American Express") {}
          public override bool ValidateCCNumber(string ccNumber){

            //....do some AmericanExpress validation
          }
      }
  }

Now comes another major reason why you want to use the ClassEnum base class. The ClassEnum assembly also offers a NHibernate usertype so that you can map your ClassEnum property in NHibernate just as you map the enum property. All you need to do is just to declare a NHibernate usertype by inheriting the generic ClassEnumUserType base class in the ClassEnum assembly.

C#
public class CreditCardTypeUserType : ClassEnumUserType<CreditCardType>{}

Now you can map your property using the following Hbm mapping XML sample:

XML
<property name="CCType" type="YourNameSpace.CreditCardTypeUserType,
   YourAssembly" column="CCTypeEnum"/>

How To Use

ClassEnum assembly is a part of the MindLib project. You can download the MindLib source package within which you will find the ClassEnum.sln in the /src folder. Also in the solution, you can find the unit test ClassEnum.Test project, where more sample code is available to show how to use this ClassEnum library.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
johannesnestler11-Dec-13 22:21
johannesnestler11-Dec-13 22:21 
SuggestionIf your issue is only that it's hard to display proper strings for enums... Pin
Aron Weiler28-Jan-13 14:03
Aron Weiler28-Jan-13 14:03 
GeneralRe: If your issue is only that it's hard to display proper strings for enums... Pin
PIEBALDconsult28-Jan-13 14:46
mvePIEBALDconsult28-Jan-13 14:46 
Hear hear! That's the way to go.
GeneralSomething else to do (Ennis Ray Lynch is right) Pin
Sergey Alexandrovich Kryukov28-Jan-08 9:48
mvaSergey Alexandrovich Kryukov28-Jan-08 9:48 
GeneralRe: Something else to do (Ennis Ray Lynch is right) Pin
Kailuo Wang28-Jan-08 10:35
Kailuo Wang28-Jan-08 10:35 
GeneralRe: Something else to do (Ennis Ray Lynch is right) Pin
PIEBALDconsult28-Jan-13 14:48
mvePIEBALDconsult28-Jan-13 14:48 
GeneralYou probably should use readonly Pin
Ennis Ray Lynch, Jr.23-Jan-08 14:02
Ennis Ray Lynch, Jr.23-Jan-08 14:02 
QuestionRe: You probably should use readonly ??? Pin
JamesHurst28-Jan-08 10:36
JamesHurst28-Jan-08 10:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.