The method String.Format has the following overload:
public static string Format (string format, params object?[] args);
which I supposed was meant for formatting many args of the same type into a string with a format for each of the args, similarly to str.format(*args) in python 3.
However, when I call:
var a = String.Format("{0} {1:0.00000000e+000} {2:0.00000000e+000}", new Double[] {1,2,3} );
I get the error:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
When I would expect the output in a to be
"1 2.00000000e+000 3.00000000e+000"
similarly to a="{0:d} {1:1.8e} {2:1.8e}".format(*[1,2,3]) in python 3.
Calling
var a = String.Format("{0}", new Double[] {1,2,3} );
fixes the error but returns in a the wrong result:
"System.Double[]"
What is the correct c# way to get the python result I expected (with different formatting for the first column)?
-
PS: This related question gives me an insight, but I'm sure there's an easier way that I'm missing:
String.Concat((new Double[] { 1,2,3 }).Select(k => string.Format("{0}", k)))
this can't be the best (or correct) way. Specially because it makes the overload String.Format(String, params object[]) useless, IMHO.
Creating an
objectarray instead of adoublearray fixes the problem:The problem is that since you are not passing an
object[]but adouble[], C# assumes that this double array is a single parameter of the params array which is of typeobject[], i.e. it passes the method an object array containing a single item being a double array.If the double values are given as an array variable, you could write:
Since the parameter is a
paramsarray, we can also simply writeOr we can use string interpolation where the numbers do not represent indexes but are the ones we want to format