Question

I have an enum that looks as follows:

public enum TransactionStatus { Open = 'O', Closed = 'C'};

and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed.

now because the data comes out of the database as an object I am having a heck of a time writing comparison code.

The best I can do is to write:

protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {
    return ((char)enum_status).ToString() == obj_status.ToString();
}

However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. Supposedly all enums inherit from System.Enum but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question.

I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing?

Was it helpful?

Solution

static void Main(string[] args)
{
    object val = 'O';
    Console.WriteLine(EnumEqual(TransactionStatus.Open, val));

    val = 'R';
    Console.WriteLine(EnumEqual(DirectionStatus.Left, val));

    Console.ReadLine();
}

public static bool EnumEqual(Enum e, object boxedValue)
{                        
    return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue));
}

public enum TransactionStatus { Open = 'O', Closed = 'C' };
public enum DirectionStatus { Left = 'L', Right = 'R' };

OTHER TIPS

Enums are generally messy in C# so when using .NET 2.0 its common to wrap the syntax with generics to avoid having to write such clumsy code.

In .NET 1.1 you can do something like the below, although it's not much tidier than the original snippet:

protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status)
{
    return (enum_status == Enum.Parse(typeof(TransactionStatus), obj_status.ToString()));
}

This is about the same amount of code but you are now doing enum rather than string comparison.

You could also use the debugger/documentation to see if obj_status really is an object or whether you can safely cast it to a string.

I would take a look at Enum.Parse. It will let you parse your char back into the proper enum. I believe it works all the way back to C# 1.0. Your code would look a bit like this:

TransactionStatus status = (TransactionStatus)Enum.Parse(typeof(TransactionStatus), obj.ToString());

If you just have to compare values you can use something like:

protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {
    return (char)enum_status == (char)obj_status;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top