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

1
  • which is good answer? Commented Mar 5, 2013 at 14:19

3 Answers 3

2
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; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

valid code, maybe even better than the original code, but doesn't answer the question
1

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; 

2 Comments

@Mohan: You're welcome. If this solved your problem, you can use the checkbox to the left of my answer to mark it "correct and accepted", this helps people who read this question in the future.
new Student(), new Student() I dont want to write this . Is it possible to make Object of Student Class single time and fill list.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.