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 constructor i.e.
If the parameters to your constructor are invalid, consider throwing ArgumentException or one of its descendant classes (e.g. ArgumentOutOfRangeException
).
You may want to use a factory class that creates instances of SomeClass returning null if the someCriteria is invalid.
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)
{
}
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.
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");
}
}
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.