Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing lists inside properties vs. in the constructor?

I have an object with List<>s exposed by properties. I generally initialize my lists within the property getter as follows:

public class Foo
{
    private List<bar> _barList;

    public List<bar>
    {
        get
        {
            if(_barList == null)
            {
                _barList = new List<Bar>()
            }

            return _barList;
        }

        set
        {
            _barList = value;
        }
    }

    public Foo()
    {
    }
}

However, my colleagues generally prefer initializing the list in the class constructor as follows:

public class Foo
{
    public List<bar> BarList { get; set; }

    public Foo()
    {
        BarList = new List<Bar>();
    }
}

Both cases prevent BarList from being accessed before it is initialized. The second seems more neat due to the use of autoproperties. The first seems like a better option though, since the list is only initialized when it is first used. Are there any other considerations I should take into account? Is there a best practice for this?

like image 858
08Dc91wk Avatar asked Jul 20 '15 09:07

08Dc91wk


1 Answers

In addition to usrs answer, there is a another answer, using C# 6.0, on this question.

One of the new features is a initializer for auto-implemented properties. You'd write:

public class Foo
{
    public List<bar> BarList { get; set; } = new List<bar>();
}

Also, have a look at the new primary constructors, found a programmers.stackexchange article.

This initializer will be called on object-initialization. In matters of memory consumption/performance, it should be equal to initializing the property in the constructor.

like image 102
Patrik Avatar answered Nov 14 '22 23:11

Patrik