Easiest way to make all strings in C# application trimmed - or decrease number of Trim() calls?
Sorry if that question has no answer.. What is the easiest and non-verbose way to make all the strings in C# application trimmed by default? Creating new Type, or extension method, or Attribute?开发者_运维知识库 Are there any hacks or settings to decrease number of Trim() calls?
UPD. Well, I have no particular case - just a lot of user input from UI or Excel or something else, and you should always keep in mind and Trim(), Trim(), Trim(). I really wonder why strings are not trimmed by default in C#.
There are plenty of drawbacks, but you could do something like:
class StringT
{
private String _s;
public StringT(String v)
{
if (!String.IsNullOrEmpty(v)) { _s = v.Trim(); }
else { _s = v; }
}
public static implicit operator StringT(String v) { return new StringT(v); }
public static implicit operator String(StringT v) { return v._s; }
}
Kinda hard to tell from the question; but I would probably create a custom textbox that overrides the Text method with Text.Trim()
Alternatively, you could create a method in a common class that would Trim whatever is passed into it. So before using any strings; you'd run them through that method first.
If you could elaborate a bit on your original question, that would help
If you mean strings that you are getting for a resource file or something, then just create a utility function that gets the strings, and call Trim()
in there, so you never need to worry about it in calling code.
If find yourself using the value in the same scope a lot then to reduce the number of times you call Trim()
the best option would be trim the value once and store it as a variable i.e.
var trimmedStr = myStr.Trim();
An extension method would be pointless as it is pretty much the equivalent of calling Trim() as I imagine you would just be doing this internally. Creating a custom type just to ensure your string has no white space is a bit over-engineering and unnecessary.
精彩评论