Object initializer
Before we can create an object without an object initializer, it takes about two steps to start with a new object and assign a value to each field. With the object initializer, a task that would otherwise require a few lines of code to complete becomes a single line of code, simplifying the code and making the code more elegant
Original wording
person person = new person ();
Person. UserName = "XXX";
Person. Age = 10;
Now the wording
person person = new Person {UserName = ' XXX ', age = 10};
Using the collection initializer, the compiler will automatically help us generate the Add insert operation, provided the collection implements the IEnumerable interface. Like the object initializer, using the collection initializer enhances the readability of the code while allowing us to write less code. The demo code is as follows.
Original wording
list<person> personlist = new list<person> ();
Personlist.add (new person {UserName = ' XXX ', age = 10});
Personlist.add (New person{username= "YYY", age=20});
Now the notation (using the collection initializer)
list<person> newpersonlist = new list<person>
{
New person{username= "XXX", age=10},
New person{username= "YYY", age=20},
};
C#_ Base, initializer