Click here to Skip to main content
Click here to Skip to main content
Go to top

A Class Based Enumeration Implementation

, 28 Jan 2013
Rate this:
Please Sign up or sign in to vote.
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:

    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.

    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:

// 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:

  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.

  public class CreditCardTypeUserType : ClassEnumUserType<CreditCardType>{}

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

 <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)

Share

About the Author

Kailuo Wang
Architect
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 2 Pinmemberjohannesnestler11-Dec-13 22:21 
SuggestionIf your issue is only that it's hard to display proper strings for enums... PinmemberAron Weiler28-Jan-13 14:03 
GeneralRe: If your issue is only that it's hard to display proper strings for enums... PinmemberPIEBALDconsult28-Jan-13 14:46 
GeneralSomething else to do (Ennis Ray Lynch is right) PinmemberSAKryukov28-Jan-08 9:48 
GeneralRe: Something else to do (Ennis Ray Lynch is right) PinmemberKailuo Wang28-Jan-08 10:35 
GeneralRe: Something else to do (Ennis Ray Lynch is right) PinmemberPIEBALDconsult28-Jan-13 14:48 
GeneralYou probably should use readonly PinmemberEnnis Ray Lynch, Jr.23-Jan-08 14:02 
When defining members using the readonly keyword on objects is usually discouraged. Although the memory reference cannot be changed the underlying object can.
 
Also, something really nice to add to class based enums is a static enumerator using the yield return keyword which is available in C# 2.0 and higher. It really makes this pattern a lot more useful.
 
Need a C# Consultant? I'm available.


Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway


QuestionRe: You probably should use readonly ??? Pinmemberjwhurst28-Jan-08 10:36 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 28 Jan 2013
Article Copyright 2008 by Kailuo Wang
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid