csharp Collection initializer

//using System.Collections.Generic;
//using System.Linq;

List<Student> lstStudent = new List<Student>()
{
	new Student{FirstName="Dhananjay", LastName="Kumar"},
	new Student{FirstName="Mritunjay", LastName ="Kumar"}
};

foreach (var r in lstStudent)
{
	Console.WriteLine(r.FirstName);
}

Console.Read();

//same using List<string>:
List<string> codes = new List<string> {
	"test",
	"test2"
};

//another option is to create an Initialiser for Student that takes the properties as parameters:
public Student(string firstName, string lastName)
{
	this.FirstName = firstName;
	this.LastName = lastName;
}

List<Student> lstStudent = new List<Student>()
{
	new Student{"Dhananjay","Kumar"},
	new Student{"Mritunjay","Kumar"}
};
Collection initializer in C# 3.0, thanks to Debug Mode.

Updated: Friday 12th November 2010, 11:16pm

There are 0 comments

Leave a comment of your own

Comments are currently closed.