C#_ Base, initializer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.