Archive for the ‘ Extension Methods ’ Category

C# Pluralize and/or Singularize

Recently I had a need to Pluralize some data elements to be displayed on screen. I didn’t want to have to write my own logic to figure do I need an”s” or  and “es” as so on. So come to find out in .NET 4 there is a class that aids in this process “System.Data.Entity.Design.PluralizationServices.PluralizationService“. Also since I’m using VS2010 and .NET 4 I get the capability to add Extension Methods to existing types. I wanted to be able to easily call the Pluralize method from any Sting.

Here is the code for the Pluralize and Singularize Extension methods for the String type.

using System;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;

public static class ExtensionMethods {
    public static String Pluralize(this String s) {
        return PluralizationService.CreateService(CultureInfo.CurrentCulture).Pluralize(s);
    }
    public static String Singularize(this String s) {
        return PluralizationService.CreateService(CultureInfo.CurrentCulture).Singularize(s);
    }
}

Now I can easily call the method on any String.

str.Pluralize();
str.Singularize();