Difference between List Index and Array Index

I encountered some exceptions from bizzar when building the connection string in my application.

string basis = "Data Source={0};Initial Catalog={1};Persist Security Info={2};User ID={3};Password={4}";
List<string> info1 = new List<string>(){ "SQLSRV", "TEST", "True", "user1", "pass1" };
string[] info2 = new string[] { "SQLSRV", "TEST", "True", "user1", "pass1" };
// throws exception
Console.WriteLine(String.Format(basis, info1));
// works fine
Console.WriteLine(String.Format(basis, info2));

Error:

An unhandled exception of type "System.FormatException" occurred in mscorlib.dll

Additional information: an index (based on zero) must be greater than or equal to zero and less than the size of the argument list.

My question is: what happened to the List index?

+4
source share
4 answers

This has nothing to do with the index. In the first case, you use this overload String.Format:

public static void Format(string format, object arg);

and in the second you use this:

public static void Format(string format, params object[] args);

, . , .

, List.

+8

. params object[] ..., .

String.Format: String Format(String format, object arg0), string Format(String format, params object[] args).

, , .

+3

string.Format() object[] .

List , . , , .

+3

MSDN

https://msdn.microsoft.com/en-us/library/b1csw23d(v=vs.110).aspx

public static string Format (string format, params object [] args)

String.Formatwants the array: params object[] argsas the second parameter, and when you provide List<String>, the entire list is treated as the first element of the array of objects, and therefore Formatfails (you have to provide five points). The easiest way: IMHO, get the array through Linq:

Console.WriteLine(String.Format(basis, info1.ToArray()));    
+3
source

All Articles