c# - Accessing a variable in an object contained within another object when the child object is null -
i have following 2 classes. addresses contains list of address. method getmailingaddress scan through addresslist looking particular type of address.
class addresses { public list<address> addresslist {get; set;} public address mailingaddress {get { return getmailingaddress();} } class address { public int? id {get; set;} }
to access id of mailingaddress type following:
addresses obj = new addresses(); int? = obj.mailingaddress.id
the problem mailingaddress can return null. if happens call fails references id through null object. in instance return null.
to work around use code:
if(obj.mailingaddress == null) { i? = null; } else { i? = obj.mailingaddress.id; }
is there way call obj.mailingaddress.id , return null if mailingaddress null without having above if statement.
i create additional method/property within class addresses again see work around, not clean solution:
public int? mailingaddressid { if(getmailingaddress == null) { return null; } else { return getmailingaddress.id; } }
first of int
struct , must use ?
or nullable<int>
making nullable , then:
int? myint = obj.mailingaddress == null ? (int?)null : (int?)obj.mailingaddress.id;
but, in c# 6 can use ?
operator called safe navigation operator :
int? myint = obj?.mailingaddress?.id;
as additional note, can use null object pattern. can learn here , use pattern also. use of null object
pattern simplifies code , makes less error prone.
Comments
Post a Comment