Static Classes and Members

A static class is a class which has only one instance. A static variable is a variable that exist per class where as normal or non-static member variables are per instance. Finally, a static method is method that can be called via class name, without creating the object of the class. Too much static things in one paragraph? Let us explain all of these concepts with the help of the following example.

´╗┐using System;
namespace CSharpTutorials {

    public static class StClass {
        public static int age = 10;
        public static void incrementAge() {
            age++;
        }

        public static int returnAge() {
            return age;
        }
    }

    public class NStClass {
        public void incrementStaticAge() {
            StClass.age++;
        }
    }

    class Tutorial {
        static void Main(string[] args)  {
            NStClass nstclass = new NStClass();
            Console.WriteLine(StClass.returnAge()); // age at the beginning
            nstclass.incrementStaticAge(); // Age will become 11
            Console.WriteLine(StClass.returnAge());
            StClass.incrementAge();// Age will become 12
            Console.WriteLine(StClass.returnAge());
            Console.WriteLine();

            Console.ReadKey();
        }
    }
}

Download the code

In the above code, a static class named StClass has been defined,inside this class a static integer type variale named age has been declared. Next a method incrementAge has been defined which is also of static type. This method increments the static age variable by one. Another static static method named returnAge has been declared which returns the current value of age.

A non static class named NStClass has also been created in the code which contains a method incrementStaticAge(). This method also increment the age variable of the StClass.

There are some general rules regarding static classes, member variables and methods. A class is defined as static after adding a static keyword after the access modifier. A static class can only contain static methods and variables since non-static methods and variables are accessed via object of the class and static class cannot be instantiated. A static method can only access static members of the class as is the case with the incrementAge and returnAge methods of the StClass which could only access static age variable. Finally a static variable has only one instance, which means that if that variable is incremented by multiple functions, its value will keep on increasing.

<<< Namespaces in C#ArrayList C# Class >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .