Mohan
Mohan

Reputation: 969

Initializing a List c#

List<Student> liStudent = new List<Student>
        {
            new Student
            {
                Name="Mohan",ID=1
            },
            new Student
            {
            Name="Ravi",ID=2

            }
        };
public 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.

Upvotes: 0

Views: 4167

Answers (3)

Michał Powaga
Michał Powaga

Reputation: 23173

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).

Upvotes: 0

Hosein Yeganloo
Hosein Yeganloo

Reputation: 504

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; }

}

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283624

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;

Upvotes: 1

Related Questions