简体   繁体   中英

Difference between index of List and index of Array

I've encountered some rather bizzar exception while constructing 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: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

My question is: what is wrong with List's index?

This has nothing to do with the index. In your first case you use this overload of 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);

So in the first case you only pass one argument. That leads to an exception because your format string expects more than one argument.

In the second case you provide all arguments because an array instead of only one List object is passed.

It sees the list as a single parameter. The array is seen as the params object[] ... parameter, giving multiple parameter values.

The problem is in the declaration of the String.Format method: The first takes String Format(String format, object arg0) , while the second takes string Format(String format, params object[] args) .

That makes the first one fail, since it expects more indexed than you supply.

The Method string.Format() accepts an object[] as parameter to replace the placeholder of the format string.

List is not an Array so it is treated as a single object. Which therefore causes the exception because you are providing less parameters than placeholders in your format string.

As you can see from MSDN

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

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

String.Format wants array : params object[] args as the second parameter, and when you provide a List<String> the entire list has been treated as the 1st item of the array of objects and so the Format fails (you have to provide five items). The easiest remedy is, IMHO, obtain an array via Linq:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM