#623 – Defining One Type Inside Another Type

You can define one type within the scope of  another one.  This is known as nesting.  The inner type can have a different accessibility level than the outer type, so it may or may not be visible from outside the outer type.

For example, we might define a DogCollar class within the Dog class.

We’ve made the DogCollar class private, which means that only code within the Dog class can use the DogCollar class.  Code outside of Dog will not be able to make use of the DogCollar type.

    public class Dog
    {
        public string Name { get; set; }
        private DogCollar myCollar;

        public Dog(string name, int collarLength)
        {
            Name = name;
            myCollar = new DogCollar(collarLength);
        }

        private class DogCollar
        {
            public int Length { get; set; }
            public DogCollar(int len)
            {
                Length = len;
            }
        }
    }
Advertisement

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

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: