1

Is it possible to instantiate a Dictonary in C# using the following syntax:

Person person = new Person();
var dictionary = new Dictionary { [person] = person };

If yes, then what version of C# supports it?

Currently I am running Visual Studio 2019 Community Edition, but it does not support this syntax.

Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • Perhaps `Dictionary dictionary = new() { [1] = person };` [see also](https://stackoverflow.com/questions/17047602/proper-way-to-initialize-a-c-sharp-dictionary-with-values) – Karen Payne Mar 11 '22 at 19:52
  • either `Dictionary dictionary = new() { {"person", person} };` or `var dictionary = new Dictionary { {"person", person} };`? – Stephan Schlecht Mar 11 '22 at 20:15

1 Answers1

0

you should write your code as blow :

Person person = new Person();
var dictionary = new Dictionary<string,person>() { "person" , person };

You can even write like this

Person person = new Person();
var dictionary = new Dictionary<string,person>() { "person" , new person {....}};