Initializing a List c#
List<Student> liStudent = new List<Student>
{
new Student
{
Name="Mohan",ID=1
},
new Student
{
Name="Ravi",ID=2
}
};
p开发者_开发百科ublic class Student
{
public string Name { get; set; }
public int ID { get; set; }
}
Is there other way to write this? I am a newbie. I want to make instance of student class first and assign properties in list.
List<Student> liStudent = new List<Student>
{
new Student("Mohan",1),
new Student("Ravi",2)
};
public class Student
{
public Student(string name,int id)
{
Name=name;
ID=id;
}
public string Name { get; set; }
public int ID { get; set; }
}
Since Student
is a reference type, you can indeed add the instances to the list first, and set their parameters afterwards:
List<Student> lst = new List<Student> { new Student(), new Student() };
lst[0].Name = "Mohan";
lst[0].ID = 1;
lst[1].Name = "Ravi";
lst[1].ID = 2;
It is going to work as you've written in Visual Studio 2008 and 2010. This way you use object initializer, there is no need to invoke a constructor. Read more on How to: Initialize Objects without Calling a Constructor (C# Programming Guide).
精彩评论