Reputation: 5832
I created a helper method that takes a string and replaces all of the newlines with HTML line breaks. I currently have the method in a helper class that needs to be called statically.
How can I simply add my helper method to the builtin C# string class?
So this is what I would like to be able to do:
m.MailingAddress = m.MailingAddress.ReplaceNewlines("<br />");
This is what I am doing currently:
m.MailingAddress = Utility.ObjectExtensions.ReplaceNewlines(m.MailingAddress,"<br />");
Upvotes: 1
Views: 4418
Reputation: 182
You can use extension method: Extension method should be declared in static class.
public static class Helper
{
public static ReplaceNewLines(this string currentStr, string replaceWith)
{
return Utility.ObjectExtensions.ReplaceNewlines(currentStr, replaceWith);
}
}
Click here for more details.
Upvotes: 1
Reputation: 424
Create extension method like this (putting your helper to method body for convenience):
public static class StringHelpers
{
public static ReplaceNewLinesExt(this string str, string replacement)
{
return Utility.ObjectExtensions.ReplaceNewlines(str, replacement);
}
}
Then after adding namespace in which your helper resides you can use extension method like that:
...
var modified = someString.ReplaceNewLinesExt("<br />");
...
You can read more about extension methods in MSDN article
Upvotes: 0
Reputation: 33139
You create a static class with extension methods, like so:
public static class StringExtensions
{
public static string ReplaceNewlines(this string text, string toReplace)
{
...
}
}
The this
keyword identifies the method as an extension, in this case to the string class.
Upvotes: 6