Translate

Friday, March 15, 2013

Why Static Class and Guidelines to use one

Question is how to prevent classes from getting instantiated and getting derived from.
  1. Have a class with private constructor 
  2. Make sure that the class is marked as sealed. 
  3. Even though we do both the class can still have instance members as a part of it, which can be used as a type to declare a variable of sealed class type, which would be useless of course. 
So in C# 2.0 the concept of static class was introduced, to prevent a class from getting instantiated one can just mark the class as static, some of the restrictions for the static classes are listed below:
You cannot have a instance property or method in a static class. The code mentioned below may not compile:
public static class MobileDevice
    {
        //This should be static too
        int broadcastBand;

        //This should be static too       
        [DllImport("user32.dll")]
        extern int DeviceIOControl(string guid);
       
        public static int BroadCastBand
        {
            get
            {
                return broadcastBand;
            }
        }

        public static int DeviceID
        {
            get
            {
                return DeviceIOControl("49ECA277-65F7-446b-9206-4C09580DDD88");
            }
        }
    }

The correct version of the class will be :
public static class MobileDevice
    {
        static int broadcastBand;
       
        [DllImport("user32.dll")]
        static extern int DeviceIOControl(string guid);
       
        public static int BroadCastBand
        {
            get
            {
                return broadcastBand;
            }
        }

        public static int DeviceID
        {
            get
            {
                return DeviceIOControl("49ECA277-65F7-446b-9206-4C09580DDD88");
            }
        }
    }
If we try to use the class by considering a static class as a type then compiler would complain: 'Cannot declare a variable of static type'
class Program
    {
        static void Main(string[] args)
        {
            MobileDevice buart = null; //'Cannot declare a variable of static type
            Console.WriteLine(MobileDevice.DeviceID);  //works
        }
    }
Also static class cannot be marked as Sealed or Abstract.

Static Class Guidelines 

http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx


Difference between Singleton and Static Class:


No comments:

Post a Comment