I'm coming from JavaScript, and I know that { }
is an object literal, not needing to require the new Object
call; I'm wondering if it's the same with C# in the {"id",id}, {"saveChangesError",true}
part.
I know there are two C# features in here, care to explain to me more about what they are?
new RouteValueDictionary()
{ //<------------------------------[A: what C# feature is this?] -------||
{"id",id}, //<------------------[B: what C# feature is this also?] ||
{"saveChangesError",true} ||
}); //<------------------------------------------------------------------||
It's a single feature - collection initializers. Like object initializers, it can only be used as part of an object initialization expression, but basically it calls
Add
with whatever arguments are present - using braces to specify multiple arguments, or single arguments at a time without the extra braces, e.g.See section 7.6.10.3 of the C# 4 spec for more information.
Note that the compiler requires two things of a type for it to be used for collection initializers:
IEnumerable
, although the compiler doesn't generate any calls toGetEnumerator
Add
methodFor example: