-2

I have this code given by the API that I'm using.

    public partial class getMerchant : object, System.ComponentModel.INotifyPropertyChanged
    {
        private int[] iMerchantIdField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("iMerchantId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
        public int[] iMerchantId
        {
            get
            {
                return this.iMerchantIdField;
            }
            set
            {
                this.iMerchantIdField = value;
                this.RaisePropertyChanged("iMerchantId");
            }
        }
    }

Now I was trying to create an object of this class and to run it:

    private void btnShowResult_Click(object sender, EventArgs e)
    {

        Awin.ApiPortTypeClient client = new Awin.ApiPortTypeClient();

        UserAuthentication userAuthentication = new UserAuthentication();
        userAuthentication.sApiKey = "111";

        getMerchant merchant = new getMerchant();

        merchant.iMerchantId[0] = 2518;
        merchant.iMerchantId[1] = 3030;


        var response = client.getMerchant(userAuthentication, merchant);

        lblResult.Text = response[0].sName.ToString();

    }

But whenever I try to run it it gives a nullreferenceexception when the compiler hit the line merchant.iMerchantId[0] = 2518; What I understood so far is that this iMerchantId[] hasn't been declared yet. But the problem is also that I can't find an answer how to declare it.

I am thankful for any help that I can get.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Chaoguo0
  • 21
  • 2

1 Answers1

2

To solve this initialize the backup property with required indices, which means the property definition would be like this:

private int[] iMerchantIdField= new int[2];

Need not to change the Public property, try using the current code, it will works fine without previous errors, since the bounds of the arrays are defined and initialized now through these backup properties.

Additional notes : If you deals with a List instead for an array, then you have to instantiate the list through the backup property, otherwise NullException will thrown. In such case the declaration would be :

private List<int> iMerchantIdField= new List<int>();
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • I'd also revisit whether this should really be an array or a `List`. – lc. Dec 05 '16 at 05:31
  • I changed the property to this: private int[] iMerchantIdField= new int[2]; The nullreferenceexception doesn't pop up anymore but I got this error code now: '**System.ServiceModel.FaultException**' How do I deal with that? – Chaoguo0 Dec 05 '16 at 17:31