Flood Gravemind
Flood Gravemind

Reputation: 3803

How do you check if a object in a class is initialized?

I have a a mainclass with various subclasses.

 public class Mainclass
    {
    public List<main> mainset { get; set; }
 // do sth to load and save model info
    }
    public class main
{
    public personalinfo info { get; set; }
    public addressinfo currentaddr { get; set; }
    public addressinfo[] otheraddr { get; set; }
    public telephone currenttel { get; set; }
    public telephone[] othertel { get; set; }
 }
public class addressinfo
{
    public string Addressline1 { get; set; } 
    public string Addressline2 { get; set; }
    public string City { get; set; }
    public string postcode { get; set; 
}
public class telephone
{
    public int tel { get; set; }
}

How do I check if the children are initialized? I have tried the following but I am getting Null exception even when I try to check for !Null.

if (main.currentaddr != null)
{
addressinfo add = new addressinfo();
//do sth
}

Upvotes: 1

Views: 5588

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

The reason this is failing is because the main variable is null. So you should check that before attempting to call currentaddr on it. It's pretty unclear from the source code you have shown where is this variable coming from and how you are initializing it but you could add the following test:

if (main != null && main.currentaddr != null)
{
    addressinfo add = new addressinfo();
    //do sth 
}

Upvotes: 6

Related Questions