English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C#3.0 (.NET 3.5introducedObject initializer syntaxThis is a new method for initializing class or collection objects. The object initializer allows you to assign values to fields or properties when creating an object without calling the constructor.
public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public int Age { get; set; } public string Address { get; set; } } class Program { static void Main(string[] args) { Student std = new Student() { StudentID = 1, StudentName = "Bill", Age = 20, Address = "New York" }; } }
In the above example, the Student class is defined without any constructor. In the Main() method, we create a Student object and simultaneously assign values to all or some of the properties within the braces. This is called object initializer syntax.
The compiler compiles the above initialization program into the following content.
Student __student = new Student(); __student.StudentID = 1; __student.StudentName = "Bill"; __student.Age = 20; __student.StandardID = 10; __student.Address = "Test"; Student std = __student;
You can use the collection initializer syntax to initialize a collection in the same way as a class object.
var student1 = new Student() { StudentID = 1, StudentName = "John" ; var student2 = new Student() { StudentID = 2, StudentName = "Steve" ; var student3 = new Student() { StudentID = 3, StudentName = "Bill" ; var student4 = new Student() { StudentID = 3, StudentName = "Bill" ; var student5 = new Student() { StudentID = 5, StudentName = "Ron" ; IList<Student> studentList = new List<Student>() { student1, student2, student3, student4, student5 };
You can also initialize a collection and an object at the same time.
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John"} , new Student() { StudentID = 2, StudentName = "Steve" , new Student() { StudentID = 3, StudentName = "Bill" , new Student() { StudentID = 3, StudentName = "Bill" , new Student() { StudentID = 4, StudentName = "Ram" } , new Student() { StudentID = 5, StudentName = "Ron" } };
You can also specify null as an element:
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John"} , null };
The initializer syntax makes the code more readable and easier to add elements to a collection.
Very useful in multithreading.