The book I'M reading "Head First C#" is trying to teach my about the use of properties, private vs public. But when viewing the following code, I still don't understand why the program is behaving the way it is.
The code shows 5 bags of feed no matter how many cows I have set in the numericUpDown1 value. But it looks like to me the line
BagsOfFeed = numberOfCows * FeedMultiplier; in the set property should set it back the way it should be anyway. There are the files.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Cow_Calculator
{
public partial class Form1 : Form
{
Farmer farmer;
public Form1()
{
InitializeComponent();
farmer = new Farmer() { NumberOfCows = 15 };
}
private void button1_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;
}
private void button2_Click(object sender, EventArgs e)
{
farmer.BagsOfFeed = 5;
}
}
}
Farmer class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cow_Calculator
{
public class Farmer
{
public int BagsOfFeed;
public const int FeedMultiplier = 30;
private int numberOfCows;
public int NumberOfCows
{
get
{
return numberOfCows;
}
set
{
numberOfCows = value;
BagsOfFeed = numberOfCows * FeedMultiplier;
}
}
}
}
One last question. How in the world would I know that the creation of Farmer should be broken into two pieces?
Farmer farmer;
and then in the public Form1 method
farmer = new Farmer() { NumberOfCows = 15 };
And how would I know the first part needs to go within in
the From class and the second part needs to go within it's Form1 method just after InitializeComponent();
Thanks for any and all replies.