C# Gripe: enum base types

As a whole I love C# but sometimes I find some quirk that I just don’t understand. I’m sure there is a reasonable explanation of why it works the way it does but I don’t know what it is.

I was building a Gtk.TreeView last night and setup an enum for each column in the TreeView. No big deal, right? The enum looks something like this:


enum Fields
{
enum1 = 0,
enum2,
enum3
}

Then, to build the column I do something like this:

TreeViewColumn col = new TreeViewColumn ();
CellRenderer NameRenderer = new CellRendererText ();
col.PackStart (NameRenderer, true);
col.AddAttribute (NameRenderer, "text", (int)Fields.Keyword);

Notice on that last line that I have to cast the enum member to an int, even though the type of the enum is int, you still have to cast its value.

You can specify the base type of an enumerator, but it defaults to an int. You could do this (and I tried) but it doesn’t change anything:


enum Fields : int
{
enum1 = 0,
enum2,
enum3
}

It would be nice to not need to cast the value of the enum, especially given the ability to explicitly set the type of the enum. I don’t know the internals of how the compiler works nor have I read the CLR specification. It’s just annoying to to tell an enum that it’s an int, only have to remind it of that fact every time you use it.

3 thoughts on “C# Gripe: enum base types

  1. I think it’s somewhat fair to require the cast, if one accepts the philosophy that the purpose of enums is to create a distinct type with a number of named values. According to this philosophy, it would be more legitimate to complain that AddAttribute uses a raw int argument rather than defining a proper descriptive enum type. The solution for naming integer arguments would then look something like this:

    public class Fields
    {
    static const int Keyword = 0;
    static const int enum2 = 1;
    // …
    }

  2. "even though the type of the enum is int"No, it isn’t.  The type of an enum is whatever the type you’ve specified; in this case the type is "Fields".  That it has a *representation* that uses integers is for the most part an irrelevant implementation detail.This is done much better in Java 5, as it happens; Java 5 finally has proper enumerated values, and there they don’t even pretend to have any representation.  But they’re also fully-fledged classes, so you can have members and methods and the like.  They’re powerful and really rather good.C# unfortuanately goes with C-style enums, albeit with the "bonus" feature that you can specify some aspects of the representation; specifically the width of the integer and the integral value.  This is a mistake.  C# enums should function as Java enums.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>