Monday, January 28, 2013

What is the difference between static, internal and public constructors?

Posted by Rahul Kharde at 8:25 AM
Static Constructor
  • Static constructor runs only ones - before the first use of the class and it can access only the static members of the class
  • Used to initialize the static members of a class.
  • Can’t access non-static members.
  • Executes before the first instance of a class. We can’t determine the time of execution.
  • Executes by the CLR not by the object of a class.
  • There are no parameterized static constructors since it is handled by the CLR not by the object.
  • Time of execution might be at the loading of contained assembly.

Public Constructor

  • Public constructor runs every time when you create an object of the class using new 
  • Public one can be called from other assemblies as well.
  • Used to restrict a class to be instantiated and to be inherited.
  • Used whenever a class contains only static members.

Internal Constructor
  • The internal constructor is only accessible to types in the same assembly
  • Internal is just another access modifier for the constructor above. It can also be private as well. This is exactly the same as access modifiers for other functions.

Example

    class ClassA
    {
        static ClassA()
        {
        }

        public ClassA()
        {
        }

        internal ClassA()
        {
        }
    }





If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top