Private Constructor
The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you do not use an access modifier with the constructor it will still be private by default. The private modifier is usually used explicitly to make it clear that the class cannot be instantiated.
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class
Private Constructor example
Notice that if you uncomment the following statement from the example, it will generate an error because the constructor is inaccessible because of its protection level.
Constructors can be marked as public, private, protected, internal, protected internal or private protected.
Private Protected
The private protected keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly
The private protected access modifier is valid in C# version 7.2 and later.
Example
A private protected member of a base class is accessible from derived types in its containing assembly only if the static type of the variable is the derived class type. For example, consider the following code segment:
-
-
- publicclassBase {
- privateprotectedint myRate = 0;
- }
- publicclassDerivedClass1: Base {
- void Access() {
- Base baseObject = newBase();
-
-
-
-
- myRate = 5;
- }
- }
-
-
- classDerivedClass2: Base {
- void Access() {
-
-
-
- }
- }
This example contains two files, Assembly1.cs and Assembly2.cs. The first file contains a public base class, Base, and a type derived from it, DerivedClass1. Base owns a private protected member, myRate, which DerivedClass1 tries to access in two ways. The first attempt to access myValue through an instance of Base will produce an error. However, the attempt to use it as an inherited member in DerivedClass1 will succeed. In the second file, an attempt to access myRate as an inherited member of DerivedClass2 will produce an error, as it is only accessible by derived types in Assembly1.
Struct members cannot be private protected because the struct cannot be inherited.