Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Mr Scapegrace Avatar asked May 30 '16 08:05

Mr Scapegrace


People also ask

What is the difference between a list and array?

List is used to collect items that usually consist of elements of multiple data types. An array is also a vital component that collects several items of the same data type. List cannot manage arithmetic operations. Array can manage arithmetic operations.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

What is the index of an array?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.


2 Answers

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.

like image 197
René Vogt Avatar answered Sep 30 '22 05:09

René Vogt


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.

like image 39
Patrick Hofman Avatar answered Sep 30 '22 04:09

Patrick Hofman