Please help me with the task: Crimes In Wonderland

Hello, I’m working on this task:

Despite the fact that Wonderland has an idyllic name, crimes are still present here. We recently noticed that one particular coder is decreasing the value of every good they buy by 1 virus in order to save on every purchase.
Change the class Good to use properties with public getters and setters. The current code should still work, but decreasing of the price should have no effect. To achieve this, change the code in the Price’s setter. You are not allowed to change any code outside of the Good class.

Here is my code:


namespace Encapsulation
{
   class Good
   {
       public string Identifier { get; set; }
       private double _price;
       public double Price 
       {
           get
           {
               return _price;
           }
           set
           {
               for (int i = 0; i < 1; i++)
               {
                   _price = value;
               }
           }
       }
   }
   class ClassWithMain
   {
       static void Main(string[] args)
       {
           var good = new Good
           {
               Identifier = Console.ReadLine(),
               Price = double.Parse(Console.ReadLine())
           };

           DecreasePrice(good);

           Console.WriteLine($"I can buy {good.Identifier} for {good.Price}.");
       }

       private static void DecreasePrice(Good good)
       {
           good.Price -= 1.0;
       }
   }
}

Can anyone please help me to solve it?

Unfortunately for loop will run over and over again on every attempt to update a value and will work on 2.
What about adding a variable like

_alreadyAssigned ?

and use it in your setter

Thank you! I made a little bit different, interesting, is my solution logically correct? (CodeEasy accepted my solution)

using System;

namespace Encapsulation
{
class Good
{
public string Identifier { get; set; }
public bool AlreadyAssigned { get; private set; }
private double _price;

    public double Price
    {
        get
        {
            return _price;
        }
        set
        { 
            if (!AlreadyAssigned)
            {
                _price = value;
            }
            AlreadyAssigned = true;
        }
    }
}

class ClassWithMain
{
    static void Main(string[] args)
    {
        var good = new Good
        {
            Identifier = Console.ReadLine(),
            Price = double.Parse(Console.ReadLine())
        };

        DecreasePrice(good);

        Console.WriteLine($"I can buy {good.Identifier} for {good.Price}.");
    }

    private static void DecreasePrice(Good good)
    {
        good.Price -= 1.0;
    }
}

}

it is correct!

1 Like