Home > Mobile >  how doesn't an exception occur when getting a zero-length substruing? C#
how doesn't an exception occur when getting a zero-length substruing? C#

Time:06-19

string jgh = "n";
string fff = jgh.Substring(1, 0);

Can you please tell me how doesn't an exception occur when I create a substring from position 1 of jgh and set th length to 0? is there something in between the n and "?
I know this is useless but I am just curious.

CodePudding user response:

In description of the method u have explanation which states :

        "Exceptions:
        T:System.ArgumentOutOfRangeException:
        startIndex plus length indicates a position not within 
        this instance. -or- startIndex
        or length is less than zero."

In other words for exception to happen sum of your starting index and length needs to be greater than length of the string or index needs to be less than zero !!

CodePudding user response:

The Microsoft reference:

   public String Substring(int startIndex, int length) {
                
    //Bounds Checking.
    if (startIndex < 0) {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
    }

    if (startIndex > Length) {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
    }

    if (length < 0) {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
    }

    if (startIndex > Length - length) {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
    }
    Contract.EndContractBlock();

    if( length == 0) {
        return String.Empty;
    }

    if( startIndex == 0 && length == this.Length) {
        return this;
    }

    return InternalSubString(startIndex, length);
}

So, startIndex must not be larger than Length, bit is allowed to be equal to Length.

Try it online!

  •  Tags:  
  • c#
  • Related