c# - Test if parent objects exists -


i using lot of database data in project exported in different classes. example, have

transaction.layout.multimedia.images.first(); 

the problem these properties not available.

so, possible transaction.layout null, possible transaction.layout.multimedia null, , on.

i use every property:

if (transaction.layout != null) {     if (transaction.layout.multimedia != null)     {         if (transaction.layout.multimedia.images != null)         {             if (transaction.layout.multimedia.images.count > 0)             {                 var img = transaction.layout.multimedia.images.first();             }         }     } } 

i wondering if there better way can check parent classes make sure property need available. these aren't objects use, there others totally different names.

thanks in advance

no, there not yet. new version of .net (roslyn) has null propagating operator.

then do:

if (transaction?.layout?.multimedia?.image?.count > 0) {     var img = transaction.layout.multimedia.images.first(); } 

for now, stuck this. minimize rows needed concatenating checks, this:

if ( transaction.layout != null      && transaction.layout.multimedia != null      && transaction.layout.multimedia.images != null      && transaction.layout.multimedia.images.count > 0    ) {     var img = transaction.layout.multimedia.images.first(); } 

there nothing more do.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -