The (newer) syntax with [ … ] = …
is required to use the set
accessor of the indexer, so you have:
tmpDict["userSpaceOnUse"] = GradientSpace.Absolute;
tmpDict["objectBoundingBox"] = GradientSpace.Relative;
while the other syntax is required to use a suitable method with the name Add
, so:
tmpDict.Add("userSpaceOnUse", GradientSpace.Absolute);
tmpDict.Add("objectBoundingBox, GradientSpace.Relative);
This difference is not an arbitrary C# compiler choice; it is required by the C# Language Specification.
For the particular type System.Collections.Generic.Dictionary<,>
, there is a difference between the two members (indexer setter vs. Add
method) when the key is already present. So if you (presumably) accidentally include the same key twice, as in:
new Dictionary<string, GradientSpace>
{
["userSpaceOnUse"] = GradientSpace.Absolute,
["objectBoundingBox"] = GradientSpace.Relative,
["userSpaceOnUse"] = GradientSpace.Relative,
}
respectively:
new Dictionary<string, GradientSpace>
{
{ "userSpaceOnUse", GradientSpace.Absolute },
{ "objectBoundingBox", GradientSpace.Relative },
{ "userSpaceOnUse", GradientSpace.Relative },
}
you will feel the difference! In the first case the last use of the key "userSpaceOnUse"
will just overwrite the first value (the first line with "userSpaceOnUse"
becomes irrelevant), while in the last case it will blow up with a DuplicateKeyException
when run.