RSS Feed for This PostCurrent Article

.NET String Enumeration

Normally you cannot use string in enum. However you can bypass using a trick, as shown below.

/// <summary>
/// Response expected from the gateway
/// </summary>
public enum Response
{
    /// <summary>
    /// No respons expected, just return the result
    /// </summary>
    [StringValue("NONE")]
    None,
    /// <summary>
    /// Error response
    /// </summary>
    [StringValue("ERROR")]
    Error,
    /// <summary>
    /// Successful response
    /// </summary>
    [StringValue("OK")]
    Ok
}

By writing a custom string attribute, using enum string is possible.

This is further described in CodeProject article here.

The only thing is that Reflection is used here, which may have performance implication.


Trackback URL


Sorry, comments for this entry are closed at this time.