-
Notifications
You must be signed in to change notification settings - Fork 0
StringExtensions
Adds convenient methods to the string class.
Today's functionality for taking left, right and mid of a string is not as easy as Left$(mystring,length), Right$(mystring,length) and Mid$(mystring,startIndex,length) from the BASIC hey days.
Feel free to take Left, Right and Mid of a string without being afraid of stepping outside the string length as we are with Substr.
"SplitAt".Left(5) => "Split"
"SplitAt".Right(2) => "At"
"SplitAt".Left(100) => "SplitAt"
"SplitAt".Mid(4,2) => "tA"
"SplitAt".Mid(5,100) => "At"
"SplitAt".Mid(6,3) => "itA"Splitting a string is often needed. The built in Split method cannot split at a certain index or with a string as splitter.
Split a string at a certain index.
"SplitAt".SplitAt(5) => [ "Split", "At" ]Split a string at a certain string.
"SplitAt".SplitAt("it") => [ "Spl", "At" ]This method is losing its value with the adoption of string interpolation.
This method will probably be deprecated.
The normal Microsoft string.Format throws an exception when the {n}s are more than the number of arguments. Throwing an exception might be ok during the development phase but maybe not later on; especially during production when logging to a file. Read this again: If a system is running in production the log files are often the only way to search for problems. We want the logging to log, not throw exception.
string.Format( "We are using {0} many {1}", "too" );Will throw an exception.
Contrary SFormat
"We are using {0} many {1}".SFormat( "too" );will render to a We are using {0} many {1}[Failed formatting. Parameter(s) missing. Parameter(s) is/are:{System.String:'too'}.]
We could also solve the above problem with inline string concatenation like so:
"We are using " + "too" + " many " + whatchagot.ToString();but if one prefers the string.Format way then there is now a safe way to do it. Besides; what happens if whatchagot is null? Exception...
- SFormat does not handle escaped {.
- As long as there is no null dot operator
class MyClass{
string MyProp{ get; set; }
}
MyClass myObject = null;
"This {0} fail".SFormat( myObject.MyProp );will fail no matter which method one uses.
log.Error( string.Format( "Method {0} threw an exception with message {1}", methodName ) ); throws an exception. Resharper warns you but without such a tool you will get a string formatting? exception at runtime and the real exception wasn't logged. That is why you have unit tests you might say but 1) do you really have 100% test coverage and 2) if you know the method succeeds no test is needed.