-1

I want to get only prices value in the console application. So if the normal value of the price is more than 30 just deduct it to 10 percent. In the set method i had to put the condition if(value > 30), but i dont know the codes not working.

class Book
{
    public string name;
    public string writer;
    public string publisher;
    private double price;
    public string category;

    public Book(string name, string writer, string publisher, double price, string category)
    {
        this.name = name;
        this.writer = writer;
        this.publisher = publisher;
        this.price = price;
        this.category = category;
    }

    public double Price
    {
        get
        {
            return price;
        }

        set
        {
            if(value >= 30)
            price = value * (.1);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Book b = new Book("Book1", "Micheal", "AB Publisher", 21.50, "Thriller");
        Book b1 = new Book("Book2", "Jones", "CD Publisher", 36.90, "History");
        Console.WriteLine(b.Price);
        Console.WriteLine(b1.Price);
    }
}
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90
yes
  • 1
  • 1

1 Answers1

1

You have several problems here:

  1. Your title should ask a question and yours doesn't. “The code is not working” is not a question anyone can answer.

  2. You didn't debug your code. If you had done that you would have seen that if Book.Price < 30 then your setter does nothing at all; it doesn't save or change anything.

  3. You're using double for prices. Doubles are binary floating-point and are designed for continuous quantities like mass or distance, not for discrete quantities like prices. For discrete floating-point use Decimal.

  4. Your setter is not idempotent. That means your Book instances will have different values depending on how you assign it. You won't see it in your example because you have only a single assignment, but as soon as you start doing things like b.Price += 1 your prices are going to start changing to unpredictable values. Do not do this ever.

The first thing you need to do is change your price field to:

private decimal price;

Then remove your Price property altogether.

You want to only display the discounted price, not change it every time you display it. The following property will do that:

public decimal DiscountedPrice => price >= 30 ? price * 0.1m : price;

Then display discounted price like this; do not change your instance variable states to display them:

Console.WriteLine(b.DiscountedPrice )
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90