#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));
        }
Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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: