Q: Exception when using reference-passed int as array index

J

Jan Killian

Hi all,
maybe you'll see the trick and could help me. I am passing int by
reference and get an exception when using it as an index to passed
array. (Yes I know I can workaround with object encapsulation, but
wish to understand this). Thanks, Jan

Code:
using System;

public class TestPassByRef {
public void printArray(string[] a) {
p = new int(0);
printArray(a, ref p);
}
private void printArray(string[] a, ref int p) {
if (p < 0 || p >= a.Length) return;
Console.Write("{0}:", p);
Console.Write("({1}) ", a[p]); // here it breaks .. see output
below
p++;
printArray(a, ref p);
}
}

public class Test {
static void Main() {
string[] a;
TestPassByRef t = new TestPassByRef();
a = new string[] {"A","B","C","D","E"};
t.printArray(a);
}
}

[output]

0:
Unhandled Exception: System.FormatException: Index (zero based) must
be greater than or equal to zero and less than the size of the
argument list.
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider,
String format, Object[] args)
at System.String.Format(IFormatProvider provider, String format,
Object[] args)
at System.IO.TextWriter.Write(String format, Object arg0)
at System.IO.SyncTextWriter.Write(String format, Object arg0)
at TestPassByRef.printArray(String[] a, Int32& p)
at TestPassByRef.printArray(String[] a)
at Test.Main()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top