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

27,303

Solution 1

The static constructor will be called the first time an object of the type is instantiated or a static method is called. And will only run once

The public constructor is accessible to all other types

The internal constructor is only accessible to types in the same assembly

On top of these three there's also protected which is only accessible to types derived from the enclosing type

and protected internal which is only accessible to types in the same assembly or those that derives from the enclosing type

and private which is only accessible from the type itself and any nested types

Solution 2

The difference between public and internal is that the internal constructor can only be called from within the same assembly, while the public one can be called from other assemblies as well.

static is a constructor that gets called only the first time the class is referenced. Static members do not belong to an instance of the class, but "to the class itself". See http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx for more information about static.

Solution 3

  • Static constructor runs only ones - before the first use of the class and it can access only the static members of the class
  • Public constructor runs every time when you create an object of the class using new
  • 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.

Your code doesn't actually compile, because the internal and the public one are the same constructor with different modifiers, which you can't do. You need to pick either internal or public (or private).

Solution 4

The static constructor is called the first time the type is used. Either in a static context or by creating an instance.

All other constructors are called when a new instance is created. The modifier just determines which code can create an instance.

If your constructor is private only the class itself and nested types can create an instance (maybe in a static factory method). This works like public/private/internal on methods.

Share:
27,303
Shankaranarayana
Author by

Shankaranarayana

Updated on December 08, 2020

Comments

  • Shankaranarayana
    Shankaranarayana over 3 years

    What is the difference between static, internal and public constructors? Why do we need to create all of them together?

     static xyz()
     {
     }
    
     public xyz()
     {
     }
    
     internal xyz()
     {
     }