Can we interrupt creating an object in constructor
Could you help me please. I have one idea but don't know how can I implement it.
So the question is: Can we interrupt creating an object in construc开发者_运维知识库tor i.e.
//Code
SomeClass someClass = new SomeClass(someCriteria);
So if someCriteria doesn't answer on our requirements we shouldn't create an object and should return null, instead of new object.
Is it possible to implement it in C#?
Best way is a factory class but if your class is so small you can use this:
class SomeClass
{
private string _someCriteria;
private SomeClass(string someCriteria)
{
_someCriteria = someCriteria;
}
public static SomeClass CreateInstance(string someCriteria)
{
if (someCriteria.Length > 2)
{
return new SomeClass(someCriteria);
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
// returns null
SomeClass someClass = SomeClass.CreateInstance("t");
// returns object
SomeClass someClass2 = SomeClass.CreateInstance("test");
}
}
You may want to use a factory class that creates instances of SomeClass returning null if the someCriteria is invalid.
It is quite usual that you check the constructor parameters if they are valid. If not, you usually throw an exception.
I also read a nice advice to provide static methods for validating constructor parameters. This enables the user of your class to check if whatever he is going to pass in the constructor will succeed or not. Those who are certain the parameters are ok (they made some sort of their validation) will go directly with the constructor.
Also consider what the user of your class will possibly do with null instead of the object (if some sort of factory class was used). Would this typically result in an NullPointerException on the next line? It's usually good idea to stop the wrong things as soon as possible, in this case throw the exception and finish. It is cleaner solution than returning null and if someone really wants to (this definetly won't be best practise) he can still catch this exception ...
If the parameters to your constructor are invalid, consider throwing ArgumentException or one of its descendant classes (e.g. ArgumentOutOfRangeException
).
The new
construct guarantees that an object will be returned (or an exception thrown). So as bleeeah recommended, a factory or similar concept will allow you to apply your logic.
That would be possible. Another way would be to put your checking in before you create the object. Like so
SomeClass someClass = null;
if (someCriteria == VALID)
{
someClass = new SomeClass(someCriteria);
}
Hope this helps.
No it is not possible directly.
You could throw an exception and add the required code to check for the exception and assign null to you variable.
A better solution would be to use a Factory that would return null if some condition fail.
var someClass = SomeClassFactory.Create(someCriteria);
if(someClass != null)
{
}
精彩评论