0

I'm writing a code in C#. Please see below codes.

    //-- Constructor
    public frmInvoice(EditInvoice editInvoice)
    {
        InitializeComponent();

        originalInfo = new EditInvoice();
        editedInfo = new EditInvoice();

        originalInfo = editInvoice;
        editedInfo = editInvoice;
        payment = new Payment();
    }

    //-- Process
    private void btnOk_Click(object sender, EventArgs e)
    {
        editedInfo.AppliedAmount = Convert.ToDouble(txtAppliedAmount.Text);
        editedInfo.PaymentCode = cboPaymentCode.SelectedValue.ToString();
        editedInfo.Remarks = txtRemarks.Text;

        if (originalInfo.AppliedAmount != editedInfo.AppliedAmount ||
            originalInfo.PaymentCode != editedInfo.PaymentCode ||
            originalInfo.Remarks != editedInfo.Remarks)
        {
            editedInfo.IsEdited = true;
        }
    }

Now the question is, why the original object **originalInfo** also changed that is supposedly not. It's annoying!

Additional: Is there a better/shortest way to compare to object (models) if have difference?

Bryan
  • 1,245
  • 5
  • 22
  • 37

1 Answers1

1

Since editInvoice is probably a reference type, you should clone it instead of assigning it directly.

http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx

Update: since you state that editInvoice is a model, it is a reference type, any class is a reference type. A struct would be a value type for example. See this article for more information: http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx

Nick N.
  • 12,902
  • 7
  • 57
  • 75
  • "No, it's not a reference type".. Although I'm skeptical, its hard to tell without seeing the implementation. – Sayse Sep 01 '14 at 06:39
  • editInvoice is a model. already successfully cloning it using MemberwiseClone. thanks! – Bryan Sep 01 '14 at 07:25
  • @Bryan nice to see that it works, I updated my answer, so you have some more information. – Nick N. Sep 01 '14 at 08:16