Search code examples
c#listprivate

list<T> property with private set


I'd like to know if this:

private List<FixedTickProvider> minorTickProviders;
public List<FixedTickProvider> MinorTickProviders { get { return minorTickProviders; } }

is equivalent to this:

public List<FixedTickProvider> MinorTickProviders { get; private set; }

the thing is: I've inherited the first piece of code, while I myself am more used to the second option. As Is was about to re-write the portion of code, I wondered if those two are exactly equivalent though.

please note that I am NOT talking about readonly Lists here. I am fully aware of the "readonly list" topic as discussed here and my question is slightly different.

NB: I am almost sure I once read an article stating that the compiler would produce the exact same code from those two extracts but I can't find it any more, nor can I find a precise answer on this subject. So please enlighten me.


Solution

  • Yes, both pieces of code will achieve the same result

    //here you are declaring a private field of class
    private List<FixedTickProvider> minorTickProviders;
    //and only exposing get to rest of the code
    public List<FixedTickProvider> MinorTickProviders { get { return minorTickProviders; } }
    
    //here you are declaring a public property which can only be set by the class which is declaring it
    public List<FixedTickProvider> MinorTickProviders { get; private set; }
    

    As far as IL is considered there will be slight difference

    In case of separate field and property following IL will be generated enter image description here

    In case of single property without backing field

    enter image description here