Can somebody tell me for what is allowed to use string.Substring(someIndex,0)?
string a = "abc";
var result = a.Substring(1,0);
Console.WriteLine(result);
This code will be compiled and will write nothing to console.
What is the reason that this is allowed?
In which case can this be used?
UPDATE
I will clarify that I know what is this method and that in this case it is returning empty string. I am NOT asking why the result is empty. I am asking why it's allowed to do this.
This code will be compiled and will write nothing to console.
First of all technically speaking, this statement is wrong: it writes a new line to the console. Thats where the Line in WriteLine comes in. But let's not be picky.
What is the reason that this is allowed?
There is no reason to disable it. Say for instance you want to make a string insertion method:
public static string StringInsert(String original, String toInsert, int index) {
return original.Substring(0,index)+toInsert+original.SubString(index);
}
Now our StringInsert method cannot know whether or first or second part will be empty (we could decide to insert at index 0). If we had to take into account that the first substring could have zero length, or the second, or both, then we would have to implement a lot of if-logic. Now we can use a one liner.
Usually one considers a string s a sequence of characters s=s0s1...sn-1. A substring from i with length j, is the string t=sisi+1...si+j-1. There is no ambiguity here: it is clear that if j is 0, then the result is the empty string. Usually you only raise an exception if something is exceptional: the input does not make any sense, or is not allowed.
Many things are allowed because there is no good reason to prohibit them.
Substrings of length zero are one such thing: in situations when the desired length is computed, this saves programmers who use your library from having to zero-check the length before making a call.
For example, let's say the task is to find a substring between the first and the last hash mark # in a string. Current library lets you do this:
var s = "aaa#bbb"; // <<== Only one # here
var start = s.IndexOf('#');
var end = s.LastIndexOf('#');
var len = end-start;
var substr = s.Substring(start, len); // Zero length
If zero length were prohibited, you would be forced to add a conditional:
var len = end-start;
var substr = len != 0 ? s.Substring(start, len) : "";
Checking fewer pre-requisites makes your library easier to use. In a way, Pythagorean theorem is useful in no small part because it works for the degenerate case, when the length of all three sides is zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With