c# - Where/How to instaniate an object to handle null reference exception -
hey guys kind of simple question, i'm not sure where/how initialize new object instance don't error. have class object(contact) has class object(contactinfo) , user decides not input(instantiate) contactinfo object. later when try search via contact.contactinfo, error. below have line of code error , have 2 classes:
foreach (var contact in contacts) { if (string.equals(contact._contactinfo.city.tolower(), city, stringcomparison.currentculture)) { contactsbycity.add(contact); } }
and 2 classes:
public class contact : person { private contactinfo info; private contactinfoloader loader; public contactinfo _contactinfo { get; set; } public contact() { } public contact(contactinfo _info) { info = _info; } public contactinfo getcontactinfo() { loader = new contactinfoloader(this); return loader.gathercontactinfo(); } } public class contactinfo { public string phonenumber { get; set; } public string address { get; set; } public string city { get; set; } public string state { get; set;} public contactinfo() { } }
if want guarantee contactinfo info
won't null after contact
constructed, you'll need check @ time of construction. consider this:
public class contact : person { private contactinfo info; public contactinfo _contactinfo { get; set; } public contact(contactinfo _info) { if (_info == null) throw new argumentnullexception("_info"); info = _info; } public contact(contactinfoloader loader) : this(loader.gathercontactinfo()) { } }
bonus:
a more standard style class definition equivalent semantics be
public class contact : person { //auto-generates private field public contactinfo info { get; private set; } public contact(contactinfo info) { if (info == null) throw new argumentnullexception("info"); this.info = info; } public contact(contactinfoloader loader) : this(loader.gathercontactinfo()) { } }
Comments
Post a Comment