Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In a generic way, you may use an expression tree and check with an extension method:</p> <pre><code>if (!person.IsNull(p =&gt; p.contact.address.city)) { //Nothing is null } </code></pre> <p>Full code:</p> <pre><code>public class IsNullVisitor : ExpressionVisitor { public bool IsNull { get; private set; } public object CurrentObject { get; set; } protected override Expression VisitMember(MemberExpression node) { base.VisitMember(node); if (CheckNull()) { return node; } var member = (PropertyInfo)node.Member; CurrentObject = member.GetValue(CurrentObject,null); CheckNull(); return node; } private bool CheckNull() { if (CurrentObject == null) { IsNull = true; } return IsNull; } } public static class Helper { public static bool IsNull&lt;T&gt;(this T root,Expression&lt;Func&lt;T, object&gt;&gt; getter) { var visitor = new IsNullVisitor(); visitor.CurrentObject = root; visitor.Visit(getter); return visitor.IsNull; } } class Program { static void Main(string[] args) { Person nullPerson = null; var isNull_0 = nullPerson.IsNull(p =&gt; p.contact.address.city); var isNull_1 = new Person().IsNull(p =&gt; p.contact.address.city); var isNull_2 = new Person { contact = new Contact() }.IsNull(p =&gt; p.contact.address.city); var isNull_3 = new Person { contact = new Contact { address = new Address() } }.IsNull(p =&gt; p.contact.address.city); var notnull = new Person { contact = new Contact { address = new Address { city = "LONDON" } } }.IsNull(p =&gt; p.contact.address.city); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload