开发者

Need help in binding values from child object to parent object

I've a class inside which there is another class array which contains most of the fields to which I need to pass the data. But When I am passing the data to parent object, I'm getting object reference not set to an instance of object error.

The scenario is something like described below:

class Request{
public PriceInfo[] Price{ get; set;}
}

class PriceInfo{
public int PriceID{get; set;} public string Country{get; set;} 
public string Package{get; set;}
}

Now in my code, I've instantiated an object of PriceInfo and assigned the appropriate values for each fields.

PriceInfo objPrice = new PriceInfo();
objPrice.PriceID = value1;
objPrice.Country = value2;

But when I try to assign the value to the parent class object, it throws the error. Say

Request objReq = new Request();
objReq.PriceInfo = objPrice  //This line throws the error. 

How do I pass the d开发者_如何学Goata in the objPrice object to the Parent object?


Add a default constructor to the Request class that initializes the PriceInfo property. You can then add objects to the array as necessary.

On a side note, use a List<PriceInfo> instead of an array. That would allow you to dynamically add or remove children without reallocating the array.


I would consider using a List instead of an Array.

public List Price{ get; set;} 

instead of:

public PriceInfo[] Price{ get; set;} 

and this:

Request objReq = new Request();
objReq.PriceInfo.Add(objPrice);

instead of:

Request objReq = new Request();
objReq.PriceInfo = objPrice;


You need to create the array first and then add the object to the array.

    objReq.Price = new PriceInfo[1];
    objReq.Price[0] = new PriceInfo();

Of course you might initialise the array within your constructor and adjust size accordingly.

List<PriceInfo> might be more useful than an array as it is more developer friendly.


you need to do this

objReq.Price[i] = objPrice

cause PriceInfo[] in parent is array of PriceInfo objects not PriceInfo Object

also before adding objects into array see if its initialized, best way is to initialize it in constructor. But I suggest you that you use List because when declaring array you need to add its size which you probably don't know, cause List of PriceInfo is dynamic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜