Reputation: 32808
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
Reputation: 2246
change method signature to:
public static string ToTitleCase(this string text) { ...
Upvotes: 2
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
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