In C# you can initialize Dictionary<TKey,TValue> like this:
var dictionary = new Dictionary<int, string>()
{
[0] = "Hello",
[1] = "World"
};
You can also initialize List<T> like this:
var listA = new List<string>()
{
"Hello",
"World"
};
The two examples listed above compile and run with no exceptions.
However, the following example compiles, but throws an exception:
var listB = new List<string>()
{
[0] = "Hello",
[1] = "World"
};
// System.ArgumentOutOfRangeException: Index was out of range.
// Must be non-negative and less than the size of the collection.
// (Parameter 'index') at System.Collections.Generic.List`1.set_Item(Int32 index, T value)
Is this an unfinished feature, since it compiles but throws an exception? If not, shouldn't this be a compilation error?
I'm using C# 12 and ASP.NET 8
is compiled to:
From the Docs:
Of course, the exception makes sense because when you initialize the list, it has zero elements. Elements at index 0 and 1 don't exist.