Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent usage of default constructor

Tags:

c#

Is there a way to prevent the usage of the default constructor?

All I can think of is throwing an exception, but I would like something that causes a compile time error.

like image 892
Farinha Avatar asked May 20 '10 16:05

Farinha


People also ask

What is a drawback of default constructor?

The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values. The default constructor initializes: All numeric fields in the class to zero. All string and object fields to null.

Is it mandatory to have default constructor?

The compiler doesn't ever enforce the existence of a default constructor. You can have any kind of constructor as you wish. For some libraries or frameworks it might be necessary for a class to have a default constructor, but that is not enforced by the compiler.

What happens if you don't declare a default constructor?

This default constructor supplied by Java as above calls the super class's no-arg constructor. If it can't find one, then it will throw an error.

When should a default constructor be removed?

There are a few reasons to delete the default constructor. The class is purely static, and you don't want users instantiating a class with only static methods/members. An example of such a class might be one that implements the factory design pattern using only static methods to create new classes.


3 Answers

  • If everything in the class is static, consider making it a static class. That way, you won't get a constructor at all.
  • If you want a parameterless constructor but you don't want it to be public, declare it explicitly and make it private (or internal etc)
  • If you don't want a parameterless constructor but do want constructors with parameters, then just declare the parameterized constructor - the default constructor won't be generated for you

I think that should cover all bases...

like image 188
Jon Skeet Avatar answered Oct 18 '22 19:10

Jon Skeet


Make it private.

So,

class SomeClass {     private SomeClass()     {     }      public SomeClass(int SomeParam)     {     } } 
like image 27
Michael Todd Avatar answered Oct 18 '22 18:10

Michael Todd


You can just make it private:

private MyClass()
{
}

Alternatively (if you didn't know already) if you just declare a constructor with parameters, the default one isn't added by the compiler, e.g.

private MyClass(string myParameter)
{
    //Can't call new MyClass() anymore
}
like image 37
Paolo Avatar answered Oct 18 '22 20:10

Paolo