0

In c#, string.format, are the arguments always computed? The below code throws index out of bound exception - does that mean that the args are computed before the result of ternary operation?

using System;
public class Program
{
    public static void Main()
    {
        int[] a = {0, 1};
        int i = -1;
        var errstr = string.Format(i < 0 ? "Wrong Index" : "value - {0}", a[i]);
    }
}
Parzival
  • 585
  • 2
  • 12

2 Answers2

4

try just

var errstr = i < 0 ? "Wrong Index" : string.Format("value - {0}", a[i]);

The below code throws index out of bound exception - does that mean that the args are computed before the result of ternary operation?

No, the ternary operator is applied to the format string, not the argument. Your arg is computed every time. In the i<0 case it becomes

var errstr = string.Format("Wrong Index", a[-1]);

which throws an exception evaluating a[-1] even though it is not referenced in the format string.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

When you do this a[i] the result will be a[-1] so the exception is correct.

  var errstr = string.Format(i < 0 ? "Wrong Index" : "value - {0}", a[i]);
MatteoCracco97
  • 426
  • 6
  • 17