Skip to content

Dictionary property initialization not following as other type #9352

Answered by HaloFour
harpalsingh1993 asked this question in Q&A
Discussion options

You must be logged in to vote

This is the expected behavior. When using the collection initialization syntax in such a manner you are adding entries to an existing collection rather than creating a new one:

// adds to existing dictionary
var dict = new TestClass {
    Data = {  {"dict1", "disct1"}, {"dict2", "disct2"}, {"dict3", "disct3"}, }
};

// creates new dictionary
var dict = new TestClass {
    Data = new Dictionary<string, string> {  {"dict1", "disct1"}, {"dict2", "disct2"}, {"dict3", "disct3"}, }
};

This only works during initialization of a type, which is why you can't do:

var dict = new Dictionary<string, string>();
dict = { "test1", "test2" };

Replies: 2 comments 6 replies

Comment options

You must be logged in to vote
6 replies
@harpalsingh1993
Comment options

@huoyaoyuan
Comment options

@umashankardotnet
Comment options

@huoyaoyuan
Comment options

@jnm2
Comment options

jnm2 May 3, 2025
Collaborator

Answer selected by harpalsingh1993
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
6 participants