Click here to Skip to main content
15,920,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
class clsCustomer {
public int custid {get; set;}
public clsOrder[] objOrders{get; set;}
}

class clsOrder{
public int OrderId {get; set;}
public int ProductId {get; set;}
public int Quantity {get; set;}
}

Need to assign values to the object of clsCustomer along with order details as below.
clsCustomer objCustomer = new clsCustomer();
objCustomer.custid = 123;
objCustomer.objOrders[0].OrderId = 25255525; (Getting null reference exception at this line.)

What I have tried:

Tried initializing clsOrder inside constructor of clsCustomer but still getting error.
Posted
Updated 18-Jul-17 0:39am
v2
Comments
F-ES Sitecore 18-Jul-17 6:25am    
objOrders is an array, so you need to reference an item at an index, like

.objOrders[0].OrderId

you can't do something like

.objOrders.OrderId

as it doesn't know which order you want to set OrderId on
Deepak.xip 18-Jul-17 6:30am    
Sorry for the typo @F-ES Sitecore.I am doing the same but still getting error.

clsCustomer objCustomer = new clsCustomer();
          objCustomer.custid = 123;
          objCustomer.objOrders = new clsOrder[] {new clsOrder() { OrderId = 25255525 } };


Creating
objOrders 
with new
clsOrder[]
and assigning
{new clsOrder() { OrderId = 25255525 } }
.
 
Share this answer
 
v2
You can't just declare an array property and just use it - it's an "empty link" when the variable is created, because the system has no idea how big the array should be.
Add code to your constructor to create the array and you should be fine:
public class clsCustomer 
   {
   public int custid {get; set;}
   public clsOrder[] objOrders{get; set;}
   public clsCustomer(int arrayNeeded = 10)
      {
      objOrders = new clsOrder[arrayNeeded];
      }
   }
 
Share this answer
 

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