tags:

views:

90

answers:

3

I've already read threads on the topic, but can't find a solution that fits.

I'm working on a drop-down list that takes an enum and uses that to populate itself. i found a VB.NET one. During the porting process, I discovered that it uses DirectCast() to set the type as it returns the SelectedValue.

See the original VB here: http://jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

the gist is, the control has

Type _enumType; //gets set when the datasource is set and is the type of the specific enum

The SelectedValue property kind of looks like (remember, it doesn't work):

    public Enum SelectedValue  //Shadows Property
    {
        get
        {
            // Get the value from the request to allow for disabled viewstate
            string RequestValue = this.Page.Request.Params[this.UniqueID];

            return Enum.Parse(_enumType, RequestValue, true) as _enumType;
        }
        set
        {
            base.SelectedValue = value.ToString();
        }
    }

Now this touches on a core point that I think was missed in the other discussions. In darn near every example, folks argued that DirectCast wasn't needed, because in every example, they statically defined the type.

That's not the case here. As the programmer of the control, I don't know the type. Therefore, I can't cast it. Additionally, the following examples of lines won't compile because c# casting doesn't accept a variable. Whereas VB's CType and DirectCast can accept Type T as a function parameter:

return Enum.Parse(_enumType, RequestValue, true);

or

return Enum.Parse(_enumType, RequestValue, true) as _enumType;

or

return  (_enumType)Enum.Parse(_enumType, RequestValue, true) ;

or

return Convert.ChangeType(Enum.Parse(_enumType, RequestValue, true), _enumType);

or

return CastTo<_enumType>(Enum.Parse(_enumType, RequestValue, true));

So, any ideas on a solution? What's the .NET 3.5 best way to resolve this?

A: 

The best .NET 2.0/3.5 way to handle it is with generics.

Sam
+3  A: 

You don't need to cast to the right type... you only need to cast to Enum. That's the declared type of the property, after all:

return (Enum) Enum.Parse(_enumType, RequestValue, true);

(I'm not really sure why Enum.Parse isn't declared to return Enum itself, to be honest. It's not like it could be any other type.)

Jon Skeet
Once I slept on it, I came to the same conclusion. Thanks!
+1  A: 
  • Generics
  • return (Enum)Enum.Parse(_enumType, RequestValue, true);

The reason second one works is because you do not need to return value as the given type, just a value as type Enum even if it is the actual enumeration underneath.

earlNameless