#630 – Nested Type May Hide Member in Outer Class

If you declare a nested type that has the the same name as a member of the outer type, the nested type hides the original member in the outer type.

For example, you might have a Dog class that defines a property named DogCollar, but a subclass of Dog that replaces the property with a nested type named DogCollar.

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

    public class Terrier : Dog
    {
        private DogCollar collar;

        public Terrier(int collarLen)
        {
            collar = new DogCollar(collarLen);
        }

        new private class DogCollar
        {
            public int Length { get; set; }

            public DogCollar(int length)
            {
                Length = length;
            }
        }
    }

When replacing a member of the outer type, you can use the new keyword to make explicit the fact that you are replacing the member in the outer type.

Advertisement