#629 – Nested Types Have Full Access to Members in Parent

When you declare a nested type, the inner type has access to everything in the parent type, even if the items in the parent are declared as private or protected.

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

        private string secretName;
        private DogCollar collar;

        public Dog(string name)
        {
            Name = name;
            secretName = "Calypso";
            collar = new DogCollar(this);
        }

        private class DogCollar
        {
            public DogCollar(Dog belongsTo)
            {
                // We can see secretName even though it is private
                Console.WriteLine(string.Format("Secret name is {0}", belongsTo.secretName));
            }
        }
    }


Note that the nested type does not automatically inherit a reference to a particular instance of the parent class. We need to pass this information into the nested type.

Advertisement