-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.

1 Answer 1

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>();
Sign up to request clarification or add additional context in comments.

2 Comments

I'd also revisit whether this should really be an array or a List.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.