+ 3

Can you prevent the instantiation of the object from the Constructor?

If somehow in the constructor you decide that the object shouldn't be created. How do you do that?

3rd Nov 2016, 11:05 PM
Eduard Alexandru
Eduard Alexandru - avatar
2 Answers
+ 3
Thank you, indeed I wanted to know if during the instantiation process I could prevent the object from being instantiated. However your suggestion will prove useful when I'll need to create an object (or not) based on some conditions, only that instead of new MyClass() I'll have to use MyClass.Create() and test if the return is an object or null. Same could be done with Java I think, but what I was truly interested l to know was if the instantiation could be prevented from the constructor, in other languages you can return false or null, in c# and Java the only way to do it is by trowing an exception I guess ? What about JS guys ?
4th Nov 2016, 7:07 AM
Eduard Alexandru
Eduard Alexandru - avatar
+ 2
If I understand correctly you want to, somehow, during instantiation prevent the object from being created? There is no mechanism in C# to do this. Except perhaps to throw an exception from the constructor. You'll have to decide if that's a good idea or not. That being said you can prevent an object from being instantiated by making a private default constructor. class SomeObject { private SomeObject() {} } Now you cannot create an instance of this class. If you are looking to add some logic during creation I would recommend you add a static method to create the instance. public static SomeObject Create(...) { // creation logic } Add this method is part of your class it can access the private constructor. You can throw and exception or return null from this method if that meets your needs. You may also want to look at some Creation Design Patterns and wrap your object instantiation login in one of those. edit: this answer is for C# I am not sure about Java or Js
4th Nov 2016, 6:05 PM
Michael Dolence