Moving Beyond Enums

Posted by: Steven Smith, on 30 Aug 2011 | View original | Bookmarked: 0 time(s)

I just published an article on ASPAlliance on Moving Beyond Enums, describing when and how to move from enums to classes in your code when you start demanding more from your enums than they were designed to give.  Check it out and let me know what you think.  I also thought Id post an alternate LINQ-ified version of the DisplayFriendlyNames() method I used in the article.

Original, non-LINQ version:

public static string DisplayFriendlyNames()
{
    var sb = new StringBuilder();
    foreach (Role role in Role.List())
    {
        if (role.IsVisible)
        {
            sb.AppendLine(role.Name);
        }
    }
    return sb.ToString();
}

LINQ version:

public static string DisplayFriendlyNames()
{
    var sb = new StringBuilder();
    Role.List().Where(r => r.IsVisible)
        .ToList()
        .ForEach(r => sb.AppendLine(r.Name));
    return sb.ToString();
}

Its up to you which one you prefer.  I generally prefer eliminating if-then conditionals wherever possible, and using LINQ for filtering.  Note the .ToList() above is needed simply to be able to use .ForEach().  You can read more about why this is necessary on Eric Lipperts blog, where youll also find an IEnumerable<T> ForEach<T> extension method.


Category: XLinq | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 1353 | Hits: 18

Similar Posts

  • Using enum strings with NHibernate persistence - level 400 more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD