lontivero
lontivero

Reputation: 5275

readonly fields initialization order

I found a class similar to the follow one:

class Controller
{
    private readonly IDataContext _myContext = new DataContext("connectionstring");

    public Controller(IDataContext context){
        _myContext = context;
    }
}

Given instances are created as bellow:

var controller = new Controller(new DataContext("anotherconnectionstring"));

What I would like to know is which will be the final instance assigned to _myContext field? The one passed as an argument or the one used as RHS in the declaration?

Upvotes: 0

Views: 60

Answers (1)

sll
sll

Reputation: 62544

All fields which are initialized explicitly in a class definition are moved into the default class/type constructor which will be called before any other explicitly defined parametrized constructor. So final value willl be a value you are passing in custom constructor.

MSDN, Fields (C# Programming Guide)

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

Upvotes: 2

Related Questions