0

Why does the C# code below allow auto-implemented properties for a List type that then results in an object reference runtime error? I realize that I can implement the getter and initialize the List but would like to know if there is a reason behind the behavior.

class Program
{
    static void Main(string[] args)
    {
        Foo foo = new Foo();
        foo.FooList.Add(3);
    }
}

class Foo
{
    public List<int> FooList { get; set; }
}

}

markm247
  • 97
  • 9
  • How would the auto property know how to create an instance of the type? – MrDosu Oct 21 '14 at 13:28
  • So to clarify, it seems to me that taking care of: FooList = new List(); would make sense. Is there another decision I would make with this property other than that which would make this not advisable? – markm247 Oct 21 '14 at 13:33
  • If you would initialize all auto-implemented properties by calling their default constructor that could cause side effects. Also, how do you want to assign `null` then? – Tim Schmelter Oct 21 '14 at 13:34
  • @TimSchmelter - What side effects? That is the essence of my question. Re null, wouldn't it be preferable to allow null assignment to be the case when you have to explicitly create getter? – markm247 Oct 21 '14 at 13:45
  • @markm247: a constructor can be arbitrarily expensive. Basically it can do anything. – Tim Schmelter Oct 21 '14 at 13:51

2 Answers2

6

It is a property, It hasn't been instantiated yet. You can instantiate it in the constructor of the class or in your Main method.

class Foo
{
    public List<int> FooList { get; set; }

    public Foo()
    {
        FooList = new List<int>();
    }
}

Or in your Main method like:

static void Main(string[] args)
{
    Foo foo = new Foo();
    foo.FooList = new List<int>();
    foo.FooList.Add(3);
}

Or with C# 6.0 you can do:

class Foo
{
    public List<int> FooList { get; set; } = new List<int>();

}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 2
    Thanks Habib. Your comment on the C# 6.0 method is very much the shorthand I was looking for and is great to know. – markm247 Oct 21 '14 at 13:41
4

You need to initialise the list in the constructor of the Foo object

class Foo
{
    public List<int> FooList { get; set; }

    public Foo()
    {
        FooList  = new List<int>();
    }

}
David Pilkington
  • 13,528
  • 3
  • 41
  • 73