Click here to Skip to main content
6,594,432 members and growing! (16,548 online)
Email Password   helpLost your password?
Languages » C# » Enumerations     Beginner License: The GNU Lesser General Public License

A Class Based Enumeration Implementation

By Kailuo Wang

A classical implementation of the enumeration using class together with NHibernate user types
C# (C# 2.0), .NET, Visual Studio, Architect, Dev
Posted:20 Jan 2008
Updated:22 Jan 2008
Views:9,340
Bookmarked:14 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
3 votes for this article.
Popularity: 2.07 Rating: 4.33 out of 5

1

2
1 vote, 33.3%
3
1 vote, 33.3%
4
1 vote, 33.3%
5

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

About the Author

Kailuo Wang


Member

Occupation: Architect
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralSomething else to do (Ennis Ray Lynch is right) PinmemberSAKryukov10:48 28 Jan '08  
GeneralRe: Something else to do (Ennis Ray Lynch is right) PinmemberKailuo Wang11:35 28 Jan '08  
GeneralYou probably should use readonly PinmemberEnnis Ray Lynch, Jr.15:02 23 Jan '08  
QuestionRe: You probably should use readonly ??? Pinmemberjwhurst11:36 28 Jan '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Jan 2008
Editor: Deeksha Shenoy
Copyright 2008 by Kailuo Wang
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project