Static class

Static class in like the normal class the feature of static class is that we can make object of static class and it contain only static members. This is also knowns as sealed class means we cannot inherit it into the child class.

Static class can have only one constructor without parameter, we cannot create parameterize constructor because to pass value of constructor we need to create object and we cannot create object of static class.

 Advantages-

It provides guarantee that object cannot be created.

It can have only one constructor without any parameter.

Let us understand with an example-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
                                
namespace ConsoleApplication10
{
   
    public static class MyMath
    {
        public static float PI = 3.14f;
        public static int cube(int n) { return n * n * n; }
    }
    public class A
    {
        public void function()
        {
            Console.WriteLine("class A");
        }
    }
    class TestMyMath
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Value of PI is: "+ MyMath.PI);
            Console.WriteLine("Cube of 3 is:"+ MyMath.cube(3));
            //MyMath obj = new MyMath();//error
            A obj = new A();
            obj.function();
           
 
        }
    } 
  
}

 

Difference between Singleton class and Static class



Singleton

 

This pattern involves a single class which is responsible to create an object


while making sure that only single object gets created. It just says that you


define only one instance and provide global access to it.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace SingleTonSample
{
    sealed class SingleTon
    {
        private static SingleTon single = new SingleTon();
        public static SingleTon Instance 
        {
            get { return single; } 
        }
        private SingleTon(){ }
        public void PrintMe()
        {
            Console.WriteLine("Singleton Class Testing");
        }
    }
}


You can visit these helpful related post.


What is a singleton in C#?

  Modified On Mar-17-2018 05:17:57 AM

Leave Comment