-1

The list doesn't add anything when the method is called, it throws an exception. How should it be done and is it possible to do without writing this:

public List<string> Mark = new List<string>();

I've done like this and this gives an exception

public class Student
{
    protected List<string> _mark;

    public List<string> Mark
    {
        get { return _mark; }
        set { _mark = value; }
    }

    public void Get()
    {
        Mark.Add("Hello");
    }
}
 static void Main(string[] args)
    {
       Student a = new Student();
        a.Get();
    }
David Shepard
  • 181
  • 2
  • 10

3 Answers3

2

That's cause you haven't created an instance of the list and so the error. It should be

private List<string> _mark = new List<string>();

Your property should just return it and no setter needed

public List<string> Mark
{
    get { return _mark; }
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
1

You don't initialize _mark. Mark.Add("Hello") causes Mark's getter to return _mark, and calling .Add on that null object causes an exception to be thrown.

You should do eg.

protected List<string> _mark = new List<string>();
hnefatl
  • 5,860
  • 2
  • 27
  • 49
0

Regarding "is it possible to do without writing this" (and a new use), the answer is no, because creating a new object might not be your intention. Consider bob in the following (contrived) example:

  List<string> jim = new List<string>();
  List<string> bob;
  //code..
  bob = jim;
  //code...

A more realistic scenario might be a List<List<string>> where you retrieve a List<string> into a variable.

zzxyz
  • 2,953
  • 1
  • 16
  • 31