I have the following sample Triangle class and I want to validate the set accessors' values, obviously I cannot have a zero side or height Triangle. But while I am writing the validation rules for each property I found myself repeating the same code over and over again. Is there a more concise way to write these properties or to group them together? You can assume how newbie to C# I am.
// The Shape class
abstract class Shape
{
// Shape's Methods
abstract public double GetArea();
abstract public double GetPerimeter();
}
// The Triangle class
class Triangle : Shape
{
private double sideA;
private double sideB;
private double baseT;
private double height;
public double SideA
{
get { return sideA; }
set
{
if (value > 0)
{
sideA = value;
}
}
}
public double SideB
{
get { return sideB; }
set
{
if (value > 0)
{
sideB = value;
}
}
}
public double BaseT
{
get { return baseT; }
set
{
if (value > 0)
{
baseT = value;
}
}
}
public double Height
{
get { return height; }
set
{
if (value > 0)
{
height = value;
}
}
}
// Triangle's constructor.
public Triangle(double sideA, double sideB, double baseT, double height)
{
this.sideA = sideA;
this.sideB = sideB;
this.baseT = baseT;
this.height = height;
}
// Get Triangle's area.
public override double GetArea()
{
return (this.baseT * this.height) / 2;
}
// Get Triangle's perimeter.
public override double GetPerimeter()
{
return sideA + sideB + baseT;
}
}
Shape
class for completeness. \$\endgroup\$