Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to initialize a C# dictionary with values

Tags:

c#

dictionary

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.

like image 313
azrosen92 Avatar asked Jun 11 '13 15:06

azrosen92


People also ask

Which is the correct way of string initialization?

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.

Should you initialize variables in C?

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.

Why do we initialize with 0 in C?

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.


2 Answers

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.

like image 129
Haney Avatar answered Nov 10 '22 01:11

Haney


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.

like image 20
Vikram Kumar Avatar answered Nov 10 '22 01:11

Vikram Kumar