I have a constructor that need to validate passed data.
public Rational(int m, int n)
If n == 0 i should inform user about that.
I know 3 ways to do that.
1) Just make return; in coustructor
2) Generate an exception
3) Create a static method that will create an object
r = new Rational();
r = Rational.GetObject(1,2);
What is the best way to validate data in constructor?
You should throw an
ArgumentOutOfRangeExceptionin the constructor.(Making sure to specify the parameter name in addition to the exception message)
In addition, you can also make a static
TryCreatemethod:or
This method would return
falseornullif the parameters are invalid instead of throwing an exception; similarly toint.TryParse.