Reputation: 307
public Planet(string planetName,string planetLocation,string distance)
{
//Is this okay to do in C#?
Name = planetName;
this.planetLocation = planetLocation;
this.galaxy = galaxy;
// etc.
}
public String Name
{
get
{
return planetName;
}
set
{
if (value == null)
{
throw new ArgumentNullException("Name cannot be Null");
}
this.planetName = value;
}
}
I created this simple example to show what I mean.
Is it okay for a C# constructor to call its own Getter/Setter Property? If the Name is null the ArgumentNullException will be thrown.
If is not recommended to call the setter property from the constructor, then how do you implement exceptions in the constructor to ensure that the name field isn't blank? or in other words if I say Planet myPlanet = new Planet(null,"9999999","Milky Way"); How do I ensure that the exception is thrown if I create my object this way?
Upvotes: 0
Views: 3143
Reputation: 4582
1) I don't know if it is common to call properties in the constructor but why not doing this? I personally call all variables directly in my constructors.
2) You could simply do this in the constructor:
if(planetname == null)
throw new ArgumentNullException("bla");
this.planetname = planetname;
So everytime planetname
equals null
a ArgumentNullException
is thrown.
If it isn't null
then the value is assigned to planetname
.
public string Name
{
get{ return name; }
set
{
value != null ? name = value : throw new ArgumentNullException("Bla");
}
}
That's the way I would do it. Maybe it helps
Upvotes: 2
Reputation: 75306
It is possible to call Set/Set property in your code works, but to follow design by contract, the better way to check null in constructor:
public Planet(string planetName,string planetLocation,string distance)
{
if (string.IsNullOrEmpty(planetName))
throw new ArgumentNullException("Name cannot be Null");
Name = planetName;
// More code lines
}
public String Name {get; private set; }
P/S: IMO, the best practice to use properties over fields and don't add more code in a property unless you really need it, just keep it simple, like this:
public String Name {get; private set; }
Upvotes: 1
Reputation: 245419
Yes, it is ok.
Any code calling the setter will throw the exception. Instead of setting the property in the constructor, you could also set it using an initializer:
// Will also throw
var planet = new Planet("999999","Milky Way"){ Name = null };
Upvotes: 3