Proper way to initialize a C# dictionary with values?Ask Questions

 Posted on 18 days ago

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

Can anyone explain what is going on here?

Share On: facebook gplus twitter
profile
Asked by Mohammad Asif on 18 days ago Score: 19 points
Add Comment:

Comments

1 Answers

0 Corrected Answers
Aproved Answers
0
Profile
Answered by Joseph Sible on 10/3/2019 9:08:42 AM Score: 25 points

With C# 6.0, you can create a dictionary in following way:

var dict = new Dictionary<string, int>

{

     ["one"] = 1,

     ["two"] = 2,

     ["three"] = 3

};

It even works with custom types.

Comments

Add Comment:

Post Your Answers

Existing Members

Sign in to your account
Email Address
Password
New Member?
Sign up and complete profile
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.