Dictionary property initialization not following as other type #9352
-
Hi Team, The dictionary behaves differently while we have declare and initialize directly vs as a property. Ex. Suppose I have class and it has property Data And If I use it Like this
The issue it doesn't show compile time error, instead it throws run time error ![]() https://dotnetfiddle.net/0o2dPX If I use the dictionary directly it shows me compile time error Thanks, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
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" }; |
Beta Was this translation helpful? Give feedback.
-
The behavior is the same. When used inside an object initializer It's consistent with other nested types: class B
{
public int Prop { get; set; }
}
class C
{
public B Nested { get; set; }
}
var c = new C
{
Nested = { Prop = 1 }
}; This also throws |
Beta Was this translation helpful? Give feedback.
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:
This only works during initialization of a type, which is why you can't do: