Hello, I am new to this field and therefore I am still learning simple things.
I make a program to store information about products in one catalog, but I don’t want to be able to put a negative price on a product or make a negative number of products in stock.
Here is my code:
public enum ProductCategory { Electric, Household, Garden, Miscellaneous } class Product { // Properties private int productID; private string productName; private double unitPrice; private double unitsInStock; // Get Product Categories public ProductCategory category { get; } // Validator for Unit Price public double UnitPrice { get { return unitPrice; } set { unitPrice = value > 0.0 ? value : 0.0; } } // Validator for Units In Stock public double UnitsInStock { get { return unitsInStock; } set { unitsInStock = value > 0.0 ? value : 0.0; } } // Constructor public Product(int productID, string productName, ProductCategory category, double unitPrice, double unitsInStock) { this.productID = productID; this.productName = productName; this.category = category; this.unitPrice = unitPrice; this.unitsInStock = unitsInStock; } // Default Constructor with Chaining public Product(int productID, string productName) : this(productID, productName, ProductCategory.Miscellaneous, 0.0, 0.0) { } // Override which returns a string with full product information public override string ToString() { return "The product " + productName + " with ID " + productID + " costs " + unitPrice + " euro per unit. We have " + unitsInStock + " items left in our " + category + " stock."; } } //Testing the app class TestProduct { static void Main(string[] args) { // Assigning correct properties to the product Product p1 = new Product(1234567, "Cake", ProductCategory.Miscellaneous, 7.5, 150); Product p2 = new Product(2345678, "Drill", ProductCategory.Household, -23, 2); Product p3 = new Product(3456789, "Shovel", ProductCategory.Garden, 12.7, -10); Console.WriteLine(p1); Console.WriteLine(p2); Console.WriteLine(p3); Console.ReadLine(); } } Here is what the console issues:
The product Cake with ID 1234567 costs 7.5 euro per unit. We have 150 items left in our Miscellaneous stock. The product Drill with ID 2345678 costs -23 euro per unit. We have 2 items left in our Household stock. The product Shovel with ID 3456789 costs 12.7 euro per unit. We have -10 items left in our Garden stock. As you can see, I have a price for Drill -23 euros, and the amount of Shovel in stock -10.
How to make it so that with negative numbers it returns 0?