I am creating a dictionary in a C# file with the following code:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT = new Dictionary<string, XlFileFormat> { {"csv", XlFileFormat.xlCSV}, {"html", XlFileFormat.xlHtml} };
There is a red line under new
with the error:
Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification
What is going on here?
I am using .NET version 2.
Highlights: There are four methods of initializing a string in C: Assigning a string literal with size. Assigning a string literal without size. Assigning character by character with size.
There is absolutely no reason why variables shouldn't be initialised, the compiler is clever enough to ignore the first assignment if a variable is being assigned twice. It is easy for code to grow in size where things you took for granted (such as assigning a variable before being used) are no longer true.
In C programming language, the variables should be declared before a value is assigned to it. In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0. Let us see another example to illustrate this.
I can't reproduce this issue in a simple .NET 4.0 console application:
static class Program { static void Main(string[] args) { var myDict = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; Console.ReadKey(); } }
Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.
With C# 6.0, you can create a dictionary in the following way:
var dict = new Dictionary<string, int> { ["one"] = 1, ["two"] = 2, ["three"] = 3 };
It even works with custom types.
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