#639 – Static Class Can Contained Nested Non-Static Class

Recall that a static class is a class that contains only static members and cannot be instantiated.

You can’t include non-static members (e.g. methods, properties) in a static class, but the static class can contain a nested non-static class.

In the example below, the static DogMethods class contains a static method, BarkALot, but also contains a nested class that can be instantiated normally.

    public static class DogMethods
    {
        public class BarkPattern
        {
            public string Sound { get; set; }
            public int NumBarks { get; set; }

            public BarkPattern(string sound, int numBarks)
            {
                Sound = sound;
                NumBarks = numBarks;
            }
        }

        public static void BarkALot(Dog d, BarkPattern pattern)
        {
            for (int i = 1; i <= pattern.NumBarks; i++)
                d.Bark(pattern.Sound);
        }
    }

 

        static void Main()
        {
            Dog d = new Dog("Kirby", 14);

            DogMethods.BarkALot(d, new DogMethods.BarkPattern("Woooooof", 3));
        }