locked
C# query-need to be solved

    Question

  • Hi all,

    Here is my code:

    Code A:

    class HappyBirthday
        {
            private int noofpresents;
            private string birthdayMassage;

            public HappyBirthday()
            {
                noofpresents = 0;
            }

            private string getMessage(string name)
            {
                string themsg;
                themsg = "Happy Birthday " + name + '\n';
                themsg += "Number of Presents = " + noofpresents.ToString();
                return themsg;
            }                

            public string  MyProperty
            {
                get { return birthdayMassage; }
                set { birthdayMassage = getMessage(value); }
            }

            public int presentCount
            {
                set { noofpresents = value; }
            }

        }

    and i am using the noofpresents property in a other class i.e Code B:

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                HappyBirthday birthdayMessage = new HappyBirthday();
                string returnmsg;

                birthdayMessage.MyProperty = "sahid";

                birthdayMessage.presentCount = 4;

                returnmsg = birthdayMessage.MyProperty;
                MessageBox.Show(returnmsg);            
            }
        }

    my problem is that when i click button1 in form it shows:

    Happy Birthday sahid

    No Of Presents = 0 in Massagebox result

    but why the property isn't setting noofpresents to 4(instead of 0)

    please help asap

    thanks in advance


    Hemant Kaushik

    Friday, July 4, 2014 7:43 AM

Answers

  • The setter of MyProperty creates the message before the number of presents is assigned.

    One way to solve this, is to just reverse the order of the assignments in the button click:

    birthdayMessage.presentCount = 4;
    birthdayMessage.MyProperty = "sahid";
    But a better solution would be to do the calculation in the getter of MyProperty, then it will always return the correct value.

    Friday, July 4, 2014 8:32 AM

All replies

  • The setter of MyProperty creates the message before the number of presents is assigned.

    One way to solve this, is to just reverse the order of the assignments in the button click:

    birthdayMessage.presentCount = 4;
    birthdayMessage.MyProperty = "sahid";
    But a better solution would be to do the calculation in the getter of MyProperty, then it will always return the correct value.

    Friday, July 4, 2014 8:32 AM
  • Thanks for the reply i got the reason behind this.

    Hemant Kaushik

    Friday, July 4, 2014 9:15 AM