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()
{
}
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()
{
}
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
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
.
new
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).
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.
You do not need to create all types of constructors. The access modifiers serve the same function as any other access modifier - to determine how the constructors can be accessed.
internal
, which is "accessible only within files in the same assembly".protected
and private
constructors operate as you expect - the constructors are accessible to items that meet the criteria for the access modifier.