Search code examples
c#recursive-datastructuresobject-initialization

In c#, does object initialization syntax happen before assignment?


In c#, does an object initialization like:

var thing = new List<object>() {new object()};

Occur before the assignment, so that it's approximately the same as:

var _thing = new List<object>();
_thing.Add(new object());
var thing = _thing;

Or does it occur after the assignment, so that it's approximately the same as:

var thing = new List<object>();
thing.Add(new object());

This would make a difference if you are trying to tie a recursive knot in a factory like:

static class AbstractFactory {
    private static readonly IEnumerable<object> _list = new List<object>() {GetIEnumerable()};

    public static IEnumerable<object> GetIEnumerable() {
        return _list;
    }
}

When _list is returned from GetIEnumerable when the method is called in the initializer for _list, will it be the new List<object>, null, or undefined?


Solution

  • It compiles down to first example i.e. object initialization occurs before assignment.

    You can look at the compiled version using .Net Reflector. It compiled down to this (extracted using reflector) -

    List<object> <>g__initLocal0 = new List<object>();
    <>g__initLocal0.Add(new object());
    List<object> thing = <>g__initLocal0;