Translate

Saturday, March 16, 2013

Public, Private and Static constructors

Here are some gotchas which we need to watch out while using public and private constructor. 
Found a really good and simple article on Code Project: 
http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C

Short notes from the article

Public Constructor

Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class.
Note one thing here: we are not making any explicit call to the constructor of base class neither by initializer nor by thebase keyword, but it is still executing. This is the normal behavior of the constructor.

Private Constructor 

Private constructors, the constructors with the "private" access modifier, are a bit special case. It is because we can neither create the object of the class, nor can we inherit the class with only private constructors. But yes, we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining.
It is possible to have the class with only the private constructors. But yes as I said, such class can neither be instantiated nor be inherited. If we try to inherit the class with only private constructors then we will get the same error as above. Also recall, once you provide constructor from your side the compiler will not add the no-parameter public constructor to your class.
Well, one of the usage scenarios of such class could be – when you have only static members in the class and you don't need to instantiate it.

What is the need of private constructor, a great answer can be found at :  
http://stackoverflow.com/questions/920045/what-is-the-need-of-private-constructor-in-c


For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)

Static Constructor 

Notes for Static Constructors:

  1. There can be only one static constructor in the class.
  2. The static constructor should be without parameters.
  3. It can only access the static members of the class.
  4. There should be no access modifier in static constructor definition.
What is the use of static constructor ? 
An amazing answer could be found at: 

A static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created
    or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write
    entries to this file.
  • Static constructors are also useful when creating wrapper classes for
    unmanaged code, when the constructor
    can call the LoadLibrary method.

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:


Singleton Pattern


Singleton Pattern: 

By having multiple reference on the web, I thought that There's no one better than Jon Skeet who could explain to me. Here's the link to the amazing article:  http://csharpindepth.com/Articles/General/Singleton.aspx

Below are some of the notes which I am scribbling from the above article to make my understanding intact: 

Standards in Service Interoperability and WSDL