Why and how does C# allow accessing private variables outside the class itself when it's within the same containing class?

I don't know if the question is descriptive enough but why and how does this behaviour exist?:

public class Layer
{
    public string Name { get; set; }

    private IEnumerable<Layer> children;
    public IEnumerable<Layer> Children
    {
        get { return this.children.Where ( c => c.Name != null ).Select ( c => c ); }
        set { this.children = value; }
    }

    public Layer ( )
    {
        this.children = new List<Layer> ( ); // Fine

        Layer layer = new Layer ( );
        layer.children = new List<Layer> ( ); // Isn't .children private from the outside?
    }
}

I can access layer.Children anywhere, that's fine, but how can I access layer.children since it's private?

Layer layer = new Layer ( );
layer.children = new List<Layer> ( );

only works if the code is inside the Layer class. Is there special code to treat accessing private variables differently if it's done inside the containing class, even though the access is from the outside?

I know the reason of using:

this.children = ...

inside the containing class, but creating new instances and modifying them from the outside, even if they are still within the containing class, doesn't seem like a good practice.

What's the reason for allowing this?

20
задан ashokgelal 19 October 2011 в 15:58
поделиться