Question

I have created a class that has an automatic property for an int variable called BagsOfFeed. I added an automatic property to prevent the value from being changed from outside the class.

I use another property that calculates the BagsOfFeed only when the NumberOfCows property is set. I have come across problem when I make BagsOfFeed readonly it prevents the NumberOfCows property from assigning a value to BagsOfFeed.

here is the class Code

namespace cow_calculator1
{
    class Farmer
    {
        public Farmer(int numberOfCows, int feedMultiplier)
        {
            this.feedMultiplier = feedMultiplier;
            NumberOfCows = numberOfCows;
        }

        public int BagsOfFeed { get { return BagsOfFeed; } }

        private int feedMultiplier;
        public int FeedMultiplier
        {
            get
            {
                return feedMultiplier;
            }
        }

        private int numberOfCows;
        public int NumberOfCows
        {
            get
            {
                return numberOfCows;
            }
            set
            {
                numberOfCows = value;
                BagsOfFeed = numberOfCows * FeedMultiplier;
            }
        }
    }
}

this is the form Code

namespace cow_calculator1
{
    public partial class Form1 : Form
    {
        Farmer farmer;
        public Form1()
        {
            InitializeComponent();
            farmer = new Farmer(15, 30);
        }

        private void calculate_Click(object sender, EventArgs e)
        {
            Console.WriteLine("I need {0} bags of feed for {1} cows", farmer.BagsOfFeed, farmer.NumberOfCows);
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            farmer.NumberOfCows = (int) numericUpDown1.Value;
        }
    }
}

this is the error

Error 1 Property or indexer 'cow_calculator1.Farmer.BagsOfFeed' cannot be assigned to -- it is read only ( "Line 38" "Column 17" cow calculator1)

Was it helpful?

Solution

You can scope a setter to be private, and remove the return value.

public int BagsOfFeed { get; private set; }

Which is roughly equivalent to

private int bagsOfFeed;

public int BagsOfFeed { 
    get { return bagsOfFeed; }
    private set { bagsOfFeed = value; }
}

Or in the second format you could just set the private backing store directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top