9 times out of 10, when I want to use the Substring()
method on a string, it's because I want to shave some characters off the END of the string, not the start. While the default Substring does have support for this, it does so by taking a second parameter which is the length of the desired string, rather than the endpoint. This means if I consistently want to shave off N characters off of a series of strings of differing length, I have to do an extra step, which can result in a good deal more code. Take for example:
//Shaving the first N chars
string trimmed = foo.bar.widget.GetType().Name.Substring(N);
vs.
//Shaving the last N chars
string trimmed = foo.bar.widget.GetType().Name.Substring(0, foo.bar.widget.GetType().Name.Length - N);
or maybe to save the extra function call, use a second line:
string name = foo.bar.widget.GetType().Name;
string trimmed = name.Substring(0, name.Length - N);
Either way, you're basically doubling the amount of code necessary to shave characters off the end of the string rather than the beginning. My modification would be simple. If you pass a negative N (which would otherwise be meaningless), it would shave -N
characters off the end of the string instead of the beginning. I can already code this up with an extension method:
public static string MySubstring(this string str, int val)
{
return (val > 0) ? str.Substring(val) : str.Substring(0, str.Length + val);
}
And then when I want to shave off the final N chars, I just do:
string trimmed = foo.bar.widget.GetType().Name.MySubstring(-N);
Short and sweet, just like shaving off the beginning characters. My question is - would it be possible to override the behavior of the default Substring() function so that I can do this without having to use my own unique name for the function? It's not like it would invalidate any existing code, because previously there was no reason to pass it a negative number, and doing so would simply throw an exception and crash. This is just one of those simple no-nonsense features that feels like it should've been part of the implementation to begin with.