Greetings everyone... I need to Trim
a String
. But I want to remove all the repeated blank spaces within the String itself, not only at the end or at the start of it. I could do it with a method like:
public static string ConvertWhitespacesToSingleSpaces(string value)
{
value = Regex.Replace(value, @"\s+", " ");
}
Which I got from here. But I want this piece of code to be called within the String.Trim()
itself, so I think I need to extend or overload or override the Trim
method... Is there a way to do that?
Thanks in advance.
There's a yes and a no to your question.
Yes, you can extend existing types by using extension methods. Extension methods, naturally, can only access the public interface of the type.
No, you cannot call this method Trim(). Extension methods do not participate in overloading. I think a compiler should even give you a error message detailing this.
Extension methods are only visible if the namespace containing the type that defines the method is using'ed.
Extension methods!
Is it possible? Yes, but only with an extension method
The class
System.String
is sealed so you can't use overriding or inheritance.Besides using extension methods -- likely a good candidate here -- it is also possible to "wrap" an object (e.g. "object composition"). As long as the wrapped form contains no more information than the thing being wrapped then the wrapped item may be cleanly passed through implicit or explicit conversions with no loss of information: just a change of type/interface.
Happy coding.
Since you cannot extend string.Trim(). You could make an Extension method as described here that trims and reduces whitespace.
You can use it like so
Gives you