You are getting the NullReferenceException because you're attempting to access the properties of a null student in your loop (you have only initialized the first two, but not the last one).
One way to avoid this exception is to do a null check in your loop, so if you haven't initialized some of the items, you can still output the names of the students who have been initialized:
foreach (student i in arr.Where(s => s != null))
{
Console.WriteLine("\nname:{0}\nmarks:{1}", i._name, i._marks);
}
You could also only show students who actually have a name (by checking for a null name) like:
foreach (student i in arr.Where(s => s != null && s._name != null))
{
Console.WriteLine("\nname:{0}\nmarks:{1}", i._name, i._marks);
}
But really something like this should probably be done in the student class itself, so the client doesn't have to. You might consider setting some default value for name in the student class, so if it isn't set you can still display something (like "No Name"), and you can also overwrite the ToString() method so that the student class knows how to display itself properly. And, while you're at it, classes and public properties are typically PascalCase in C#:
public class Student
{
private string _name;
public string Name
{
get { return _name; }
set { if (value != null) _name = value; }
}
public int Marks { get; set; }
public Student()
{
Name = "<No Name>";
}
public override string ToString()
{
return string.Format("{3}Name:{0}{3}Marks:{1}",
Name, Marks, Environment.NewLine));
}
}
With this in place, you can then do something simpler like:
foreach (student i in arr.Where(s => s != null))
{
Console.WriteLine(i);
}