I'm new to C#. I'm trying to create a class named 'Product'. It has some variables named "productName", "discountRate", "productPrice". I want to calculate new price with using productPrice(e.g. 6000) and discountRate(e.g. 10). If discountRate is 0, then it should return productPrice, if discountRate is not 0, then it should return the new price.
productPrice - ((productPrice * discountRate) / 100)
But I'm getting this error:
An unhandled exception of type 'System.StackOverflowException' occurred in Class_intro.dll
Here's my code:
using System;
namespace Class_intro
{
class Program
{
static void Main(string[] args)
{
Product product1 = new Product();
product1.productName = "Huawei Notebook";
product1.discountRate = 10;
product1.productPrice = 6000;
Product product2 = new Product();
product2.productName = "Lenovo Notebook";
product2.discountRate = 25;
product2.productPrice = 4000;
Product[] products = new Product[] { product1, product2 };
foreach (var product in products)
{
Console.WriteLine("Product Name: " + product.productName
+ "\nProduct Price: " + product.productPrice
+ "\nDiscount Rate: " + product.discountRate
+ "\n-----------------");
}
}
}
class Product
{
public string productName { get; set; }
public int discountRate { get; set; }
public double productPrice
{
get
{
if (discountRate == 0)
{
return productPrice;
}
else
{
return productPrice - ((productPrice * discountRate) / 100);
}
}
set { productPrice = value; }
}
}
}
The reason for the error is referencing the property in both the getter and setter, which causes an infinite loop, but your design is a bit confusing since you use the same property for the "gross" product price and the "discounted" product price. I would just use a plain property for the product price and a separate read-only property for the discounted price. That also gets rid of the infinite loop:
class Product
{
public string productName { get; set; }
public int discountRate { get; set; }
public double productPrice {get; set;}
public double discountedPrice
{
get
{
return productPrice - ((productPrice * discountRate) / 100);
}
}
}
Note that you don't need the if (discountRate == 0)
case because mathematically it's the same, but if you want to keep it in there for readability that's fine.