Collection
Collection type initializer (Collection initializers)
Want to see a "strange" code:
1class Program
2 {
3 static void Main (string[] args)
4 {
5 var a = new Point {x = ten, y = 13};
6 var b = new Point {x =, y = 66};
7
8 var r1 = new Rectangle {p1 = A, p2 = b};
9 Console.WriteLine ("R1:P1 = {0},{1}", P2 = {2},{3} ",
10 r1.p1.x, R1.p1.y, r1.p2.x, R1.P2.Y);
One
12 var c = new Point {x =, y =};
13 var r2 = new Rectangle {p2 = c};
15 Console.WriteLine ("R2:p1 = = {0}, P2 = {1}, {2} ',
16 r2.p1, r2.p2.x, R2.P2.Y);
17 }
18 }
20 public class point
21 {
22 public int x, y;
23 }
24 public class Rectangle
25 {
26 public point P1, p2;
27 }
Do you notice the initialization syntax for the collection type? Straightforward!
This is also a new feature in the C # 3.0 syntax specification.
Perhaps the following example illustrates the problem more:
This is our previous wording:
1class Program
2 {
3 private static list<string> keywords = new list<string> ();
4
5 public static void Initkeywords ()
6 {
7 keywords. ADD ("while");
8 keywords. ADD ("for");
9 keywords. ADD ("break");
keywords. ADD ("switch");
one by one keywords. ADD ("new");
keywords. ADD ("if");
keywords. ADD ("Else");
14}
15
public static bool Iskeyword (string s)
17 {
return keywords. Contains (s);
19}
static void Main (string[] args)
21 {
initkeywords ();
String[] Totest = {"Some", "identifiers", "for", "testing"};
24
foreach (string s in Totest)
if (Iskeyword (s)) Console.WriteLine ("' {0} ' is a keyword", s);
27}
28}
This is our notation in C # 3.0:
1class Program
2 {
3 private static list<string> keywords = new List<string> {
4 ' while ', ' for ', ' break ', ' switch ', ' new ', ' if ', ' Else '
5};
6
7 public static bool Iskeyword (string s)
8 {
9 return keywords. Contains (s);
10}
11
static void Main (string[] args)
13 {
String[] Totest = {"Some", "identifiers", "for", "testing"};
15
foreach (string s in Totest)
if (Iskeyword (s)) Console.WriteLine ("' {0} ' is a keyword", s);
18}
Does the
19} become initialized like an enumeration type?
personally think it's helpful to improve the reading quality of the code,
otherwise a bunch of add () look not concise, feel very long-winded.