Saturday, December 26, 2009

Static Class for Beginners

In general, the members of a class can be accessed by instance of that class when they are in public, but there comes a situation to access or call members of a class without an instance and this can be achieved by declaring them as static.


How to create a static class and access in our application?


Step 1: Create a Static class name as "StaticExample"



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace KumarConsoleApplication
{
    public static class StaticExample
    {
        public static int AddNum(int num1, int num2)
        {
            return num1 + num2;
        }
        public static int SubNum(int num1, int num2)
        {
            return num1 - num2;
        }
    }
}


Step 2: Add reference of the above class in our application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KumarConsoleApplication;


namespace OurApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Addition " + StaticExample.AddNum(10, 20));
            Console.WriteLine("Substraction " + StaticExample.SubNum(30, 10));
            Console.Read();
        }
    }
}






Step 3: Run the application and see the output in console application


The output is :
Addition 30
Substraction 20


Features:
  • Static classes can not be instantiated.
  • Static classes are sealed so they can not be inherited.
  • Static class is preceded by keyword static.
  • Static constructor of static class called only once.
  • Static class can have only static members which means only static members are allowed. 
  • Static class has private constructors.
  • Member of the Static class can be accessed by class name itself.
  • Static classes can only have static constructor to initialize static members.   class has private constructors.
Hope this article gave you some idea about static classes


Happy coding and learning

0 Comments:

blogger templates | Make Money Online