How do I DYNAMICALLY cast in C# and return for a property

Posted by ken-forslund on Stack Overflow See other posts from Stack Overflow or by ken-forslund
Published on 2010-05-11T03:57:35Z Indexed on 2010/05/11 4:04 UTC
Read the original article Hit count: 314

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about casting