#517 – Static Classes

A static class is a class that contains only static members and cannot be instantiated.  You declare a class as static using the static keyword.

A static class:

  • Can only have static members (can’t contain instance members)
  • Cannot be instantiated
  • Cannot serve as the type of a variable
  • Cannot serve as a parameter type
  • Cannot inherit from another class
  • Cannot serve as a parent of another class
    public static class DogMethods
    {
        private static int NumBarks = 5;

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

        public static string MarriedName(Dog d1, Dog d2)
        {
            return d1.Name + d2.Name;
        }
    }
            Dog d1 = new Dog("Kirby", 12);
            Dog d2 = new Dog("Lassie", 47);

            DogMethods.BarkALot(d1);
            Console.WriteLine(DogMethods.MarriedName(d1, d2));

Advertisement

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

2 Responses to #517 – Static Classes

  1. Pingback: #639 – Static Class Can Contained Nested Non-Static Class « 2,000 Things You Should Know About C#

  2. Pingback: #783 – When to Create a Static Class « 2,000 Things You Should Know About C#

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 )

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: