Charles Charles - 10 months ago 41
C# Question

C# startIndex + length > this.length

I`m experimenting a weird issue. I code a huge amount of data ( an struct ) into an hex string and upload to the server as varbin. Then I download it and, sometimes it cant be decoded. So I decided to code some prints:

public static void d(String TAG, String message)
int maxLogSize = 1000;
for (int i = 0; i <= message.Length / maxLogSize; i++)
int start = i * maxLogSize;
int end = (i + 1) * maxLogSize;
if (end > message.Length - 1)
end = message.Length - 1;
//end = end > message.Count() ? message.Count() : end;
print(message.Substring(start, end));
print("start: " + start.ToString() + " end: " + end.ToString() + " size: " + message.Length);

then in the try/catch of the server response coroutine I get this:

11-03 15:03:02.616 13103-13117/com.Mindfunk.minus I/Unity: start: 63000 end: 64000 size: 127834

(Filename: ./artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 37)
11-03 15:03:02.636 13103-13117/com.Mindfunk.minus I/Unity: There was an error decoding this challenge replay . Maybe it is corrupted.
System.ArgumentOutOfRangeException: startIndex + length > this.length
Parameter name: length
at System.String.Substring (Int32 startIndex, Int32 length) [0x00000] in <filename unknown>:0
at DBConnection+Log.d (System.String TAG, System.String message) [0x00000] in <filename unknown>:0
at DBConnection+<DownloadChallengeReplay>c__IteratorE.MoveNext () [0x00000] in <filename unknown>:0

I don't know why it can't read after half of the string, only thought about the size, because with not so big sets of data it works like a charm.

log2(64000) is approximately 16. I'm assuming max length for a C# string is 16 bits but surprise! I found it is 32 bits. Thinking about
as not at all correlated methods, but why?

Answer Source

start: 63000 end: 64000

 message.Substring(start, end)

The second argument to Substring is the length of the string to extract. You are telling it to start at position 63000 and retrieve the next 64000 characters.