Reputation: 3568
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?
Upvotes: 3
Views: 2759
Reputation: 245489
Considering you're dealing with an invalid argument being passed into the constructor, I would probably throw a new ArgumentException
from inside the constructor.
Upvotes: 8
Reputation: 620
I'd go with throwing an System.ArgumentException
from the constructor.
Upvotes: 0
Reputation: 888205
You should throw an ArgumentOutOfRangeException
in the constructor.
(Making sure to specify the parameter name in addition to the exception message)
In addition, you can also make a static TryCreate
method:
public static bool TryCreate(int m, int n, out Rational result);
or
public static Rational? TryCreate(int m, int m);
This method would return false
or null
if the parameters are invalid instead of throwing an exception; similarly to int.TryParse
.
Upvotes: 2
Reputation: 839144
Two things:
ArgumentOutOfRangeException
in the constructor.Upvotes: 2
Reputation: 755044
Generate an exception: you can't afford to let the user play with (create) an object that won't work.
Upvotes: 1