#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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Rock says:

    how can we access members of nested class in the outer class?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: