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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With