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

Advertisements

#626 – Nested Type Options

When you declare one type inside of another, the outer type must be either a class or a struct.  The inner (nested) type can be one of the following: class, struct, interface, delegate or enum.

Here are a few common examples.

A struct in a class:

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

        public struct DogCollar
        {
            public int Length;
            public string Material;
        }
    }

A delegate type  defined in a class:

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

        public delegate void BarkHandler(object sender, BarkEventArgs e);
    }

An enum in a class:

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

        public enum Temperament { Docile, Excitable, Vicious };
    }