Click here to Skip to main content
15,892,199 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
C#
public partial class OrderWS
{
    private FulfillmentWS[] fulfillmentListField;
    public FulfillmentWS[] fulfillmentList
     {
         get
        {
           return this.fulfillmentListField;
         }
         set
         {
          this.fulfillmentListField = value;
         }
      }
}

public partial class FulfillmentWS
{
   private string fulfillingOutletIdField;
   public string fulfillingOutletId
        {
            get
            {
                return this.fulfillingOutletIdField;
            }
            set
            {
                this.fulfillingOutletIdField = value;
            }
        }
}


Both the classes are in same *.cs file. I'm trying to access fulfillingOutletIdField variable and assign a vlue to it, as below.
C#
OrderWS WPObj = new OrderWS();
WPObj.fulfillmentList = new FulfillmentWS[1];       WPObj.fulfillmentList[1].fulfillingOutletId = "1234";

But I've an error in last line, saying "Array Index Out of bounds"

Any help would be appreciated..

Thanks !
Posted
Updated 26-Jul-15 21:59pm
v2

1 solution

Look at your code:
C#
WPObj.fulfillmentList = new FulfillmentWS[1];
WPObj.fulfillmentList[1].fulfillingOutletId = "1234";
You declare an array with one element, and that try to access the second element of it - C# uses zero based indexes I'm sure you remember! :laugh:


"Even if I add
C#
WPObj.fulfillmentList[0].fulfillingOutletId = "1234";
I've "Object reference not set..." error, I'm looking for an aswer"



Well yes - you will.
Think about it: You allocated an array of one element to WPObj, but that array doesn't automatically fill itself with new objects - it's an array of null values.
You need to create the array, fill it with objects, and then access them.
C#
WPObj.fulfillmentList = new FulfillmentWS[1];
WPObj.fulfillmentList[0] = new FulfillmentWS();
WPObj.fulfillmentList[0].fulfillingOutletId = "1234";


To be honest, I'd use a List rather than an Array, and create the collection instance inside the class, rather than leaving it up to the outside world.
 
Share this answer
 
v2
Comments
Chaitanya Phani Kumar 25-Jul-15 4:19am    
Even if I add WPObj.fulfillmentList[0].fulfillingOutletId = "1234"; I've "Object reference not set..." error, I'm looking for an aswer
OriginalGriff 25-Jul-15 4:51am    
Answer updated.
Artem Kulikov 27-Jul-15 5:30am    
Agree with OriginalGriff.
By the way, you can also initialize it with shorter version:
WPObj.fulfillmentList = new[] {new FulfillmentWS()};

instead of this variant:
WPObj.fulfillmentList = new FulfillmentWS[1];
WPObj.fulfillmentList[0] = new FulfillmentWS();

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900