Samantha J T Star
Samantha J T Star

Reputation: 32808

How can I change the ToTitle function to be a string extension?

I recently saw a post asking if there was a way to change a string so it started with an uppercase and had lowercase following. Here looks to be the best solution:

public static class StringHelper {     
   public static string ToTitleCase(string text)     {
      return StringHelper.ToTitleCase(text, CultureInfo.InvariantCulture);     
   }         
   public static string ToTitleCase(string text, CultureInfo cultureInfo)     {         
      if (string.IsNullOrEmpty(text)) return string.Empty;             
      TextInfo textInfo = cultureInfo.TextInfo;         
      return textInfo.ToTitleCase(text.ToLower());     
   } 
}

What I would like is to convert these into string extensions. Can someone suggest how I can do this?

Upvotes: 3

Views: 215

Answers (3)

wiero
wiero

Reputation: 2246

change method signature to:

  public static string ToTitleCase(this string text) { ...

Upvotes: 2

vc 74
vc 74

Reputation: 38179

public static class StringHelper {     
   public static string ToTitleCase(**this** string text)     {
      return StringHelper.ToTitleCase(text, CultureInfo.InvariantCulture);     
   }         
   public static string ToTitleCase(**this** string text, CultureInfo cultureInfo)     {         
      if (string.IsNullOrEmpty(text)) return string.Empty;             
      TextInfo textInfo = cultureInfo.TextInfo;         
      return textInfo.ToTitleCase(text.ToLower());     
   } 
}

Upvotes: 3

Oded
Oded

Reputation: 499012

Use the this keyword in front of the first parameter:

public static class StringHelper
{     
   public static string ToTitleCase(this string text)
   {
      return StringHelper.ToTitleCase(text, CultureInfo.InvariantCulture);     
   }         

   public static string ToTitleCase(this string text, CultureInfo cultureInfo)
   {         
      if (string.IsNullOrEmpty(text)) return string.Empty;             
      TextInfo textInfo = cultureInfo.TextInfo;         
      return textInfo.ToTitleCase(text.ToLower());     
   } 
}

See How to: Implement and Call a Custom Extension Method (C# Programming Guide) on MSDN.

Upvotes: 8

Related Questions