What C # function allows you to use object literal notation?

I come from JavaScript, and I know that { } is an object literal, not requiring a call to new Object ; I am wondering if this matches C # in terms of {"id",id}, {"saveChangesError",true} .

I know there are two C # possibilities here, tell 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} || }); //<------------------------------------------------------------------|| 
+6
source share
2 answers

This is the only function - collection initializers . Like object initializers, it can only be used as part of an object initialization expression, but basically it calls Add with any arguments — using curly brackets to specify multiple arguments or single arguments at a time without additional curly braces, for example

 var list = new List<int> { 1, 2, 3 }; 

See Section 7.6.10.3 of the C # 4 Specification for more information.

Note that for collection initializers, you need to use two things like:

  • It should implement IEnumerable , although the compiler does not call GetEnumerator calls
  • It must have appropriate overloads for the Add method.

For instance:

 using System; using System.Collections; public class Test : IEnumerable { static void Main() { var t = new Test { "hello", { 5, 10 }, { "whoops", 10, 20 } }; } public void Add(string x) { Console.WriteLine("Add({0})", x); } public void Add(int x, int y) { Console.WriteLine("Add({0}, {1})", x, y); } public void Add(string a, int x, int y) { Console.WriteLine("Add({0}, {1}, {2})", a, x, y); } IEnumerator IEnumerable.GetEnumerator() { throw new NotSupportedException(); } } 
+8
source

This collection initialization syntax. It:

 RouteValueDictionary d = new RouteValueDictionary() { //<-- A: what C# feature is this? {"id",id}, //<-- B: what C# feature is this also? {"saveChangesError",true} }); 

basically equivalent to this:

 RouteValueDictionary d = new RouteValueDictionary(); d.Add("id", id); d.Add("saveChangesError", true); 

The compiler recognizes the fact that it implements IEnumerable and has the appropriate Add method and uses it.

See: http://msdn.microsoft.com/en-us/library/bb531208.aspx

+7
source

Source: https://habr.com/ru/post/913086/


All Articles