2

In our application we work with DataTables a lot. This is dictated by the interface to a another system. Often a column in one of these DataTable's is in fact an enumeration, which is then of a Int16 datatype. Currently we use magic constants all over the place, but that isn't pretty. A real enum would be much better, but how can you write an elegant comparison? Especially considering that a DBNull is also sometimes a valid value.

Ideally we would write this:

if ( tbl.Rows[0]["EnumColumn"] == MyEnum.SomeValue )
    // Do stuff

But, naturally, that will not work. The closest to what I can come is:

if ( tbl.Rows[0]["EnumColumn"] != DBNull.Value && Convert.ToInt32(tbl.Rows[0]["EnumColumn") == (int)MyEnum.SomeValue )
    // DO stuff

Which looks plain ugly. Any ideas on how to make this prettier and easier to write?

Vilx-
  • 104,512
  • 87
  • 279
  • 422

1 Answers1

3

It should be something like this:

tbl.Rows[0]["EnumColumn"] != DbNull.Value && Convert.ToInt32(tbl.Rows[0]["EnumColumn"]) == MyEnum.SomeValue

I would make a static method for it:

    public enum TestEnum
    {
        A = 1,
        B = 2
    }

    public static bool EqualsTestEnum(object value, TestEnum enumValue)
    {
        if (value == null || value == DBNull.Value)
        {
            return false;
        }

        int i;
        if (int.TryParse(value.ToString(), out i))
        {
            return i == (int) enumValue;
        }

        return false;
    }
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
  • Will throw an exception on `DBNull`. Oh, sorry, my example had a mistake about this. Fixed. – Vilx- Apr 20 '11 at 11:43
  • I think this new code will work better. I actually would love to use a generic, but it doesn't seem to work in my compiler :( – Kees C. Bakker Apr 20 '11 at 11:50
  • Check here: http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum – Vilx- Apr 20 '11 at 12:00
  • @Vilx In our framework we use something that converts values to enums. Every enum has a None value, so we know that a conversion didn't work (we don't like to use tryparse and out). – Kees C. Bakker Apr 20 '11 at 12:04
  • I guess that a static method is the best anyway. OK, I'll go with that. – Vilx- Apr 20 '11 at 13:24