I have following code snippet in c#
public class Customer
{
public Customer()
{
PhoneList = new List<PhoneNumber>();
}
public Customer(int id, string name)
{
this.CustomerID = id;
this.CustomerName = name;
}
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public List<PhoneNumber> PhoneList { get; set; }
}
using System;
using Sy开发者_如何学Pythonstem.Collections.Generic;
using System.Linq;
using System.Text;
public class PhoneNumber
{
public int ID { get; set; }
public int Number { get; set; }
public PhoneNumber()
{
}
public PhoneNumber(int id, int number)
{
this.ID = id;
this.Number = number;
}
}
I am using these classes in UI as bellow
protected void Page_Load(object sender, EventArgs e)
{
List<Customer> list = new List<Customer>();
list.Add(new Customer(2, "John"));
list.Add(new Customer(3, "Joe"));
list.Add(new Customer(4, "Don"));
**list[0].PhoneList.Add(new PhoneNumber(1, 1231213));//Object reference not set to an instance of an object.**
list[0].PhoneList.Add(new PhoneNumber(1, 1231213));
GridView1.DataSource = list;
GridView1.DataBind();
}
When I am executing the page getting Object reference not set to an instance of an object. error message.
While you create Customer.PhoneList
in Customer
's default constructor you don't create it in the id/name constructor. Either add
PhoneList = new List<PhoneNumber>();
to the second constructor, or chain the constructors with this()
syntax:
public Customer(int id, string name) : this()
{
this.CustomerID = id;
this.CustomerName = name;
}
which will call the default constructor first.
Each of the constructors in Customer
needs to initialise the PhoneList
collection. You're calling the constructor override that takes Id
and Name
and it doesn't initialise the collection. Change that constructor as follows:
public class Customer
{
public Customer()
{
PhoneList = new List<PhoneNumber>();
}
public Customer(int id, string name)
: this()
{
this.CustomerID = id;
this.CustomerName = name;
}
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public List<PhoneNumber> PhoneList { get; set; }
}
You are not initialising PhoneList in the Customer(int id, string name)
constructor, it is therefore null when you add new customers.
null is the default value for reference types. Because you don't initialize your PhoneList before it's usage, it remains to be null and you get this exception
Have you considered initializing PhoneList property in your constructor with parameters? ;)
public Customer(int id, string name)
{
PhoneList = new List<PhoneNumber>(); //this constructor is call
this.CustomerID = id;
this.CustomerName = name;
}
You did not add PhoneList in the other constructor which is being called in your code, So its never initialised
Try doing
public Customer(int id, string name) : this()
{
this.CustomerID = id;
this.CustomerName = name;
}
精彩评论