This does not prevent the need to call a constructor. The default
constructor of the type will still be called. That means this will not work if the type has
a private parameterless constructor, as the default constructor will
not be accessible. This will also not help avoid situations in which a
new instance is needed of a type that is unknown until runtime. There is a need for a way to create a new instance of a type, without calling any constructor, as the types default constructor may not be accessible, or
it may perform actions that are undesired.
public class TestClass1 {
public TestClass1() {
Console.WriteLine("TestClass1 constructor called.");
}}
public class TestClass2 {
private TestClass2() {
Console.WriteLine("TestClass2 constructor called.");
}}
//////////////////
static void Main() {
TestClass1 test1 = new TestClass1 { }; // Output: TestClass1 constructor called.
TestClass2 test2 = new TestClass2 { }; // Compile error, TestClass2.TestClass2()' is inaccessible due to its protection level
}