Is there a way to refuse to create the object in constructor method?
My point is to set an extra parameter related to a condition.
For example:
public Test(Rule rule){
if(rule == Rule.Custom)
//DO NOT CREATE
else{
this.rule = rule;
}
}
//WORK IF rule IS Custom
//I want to pass this information to user
public Test(Rule rule, string extra){
if(rule != Rule.Custom)
//DO NOT CREATE
else{
this.rule = rule;
this.extra = extra;
}
}
Maybe i can make a factory method but i am curious about a workaround.
If your purpose is to not throw an exception but to just not create the object, then a factory method is your only real option. That has two models:
bool TryCreate(parameters ..., out Result)signature, where a boolean is returned to the call signifying success or failure.Of course, the real problem with these is that the caller cannot know why the object creation failed and will need to consult some out of band information (documentation) for further info.