-1

I have List of Albums objects (photo albums for example). I check properties of the object is null.

Just example:

if (albums.Last() != null 
      && albums.Last().Photos != null 
      && albums.Last().Photos.Description != null) { //action }

Can I do this check shorter in code?

Alexandr
  • 1,891
  • 3
  • 32
  • 48

4 Answers4

4

Just wrap it in a function:

public static bool IsInitialized(a Album) {
    return a != null &&
        a.Photos != null &&
        a.Photos.Description != null;
}

Then your calling code becomes:

var album = albums.LastOrDefault();

if (Album.IsInitialized(album)) {
    // its fine
}
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
2

You can't.

BTW:

  1. use vars instead of calling a function all the time(Last()).

  2. use LastOrDefault() and prevent crashes.

    var lastAlbum = albums.LastOrDefault();
    if(lastAlbum != null && lastAlbum.Photos != null && lastAlbum.Photos.Description != null){//action}
    
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
2

You could use an Extension Method -

public static class ListExtension {
     public static bool IsLastPhotoNotNull(this List<Album> albums){
          var album = albums.LastOrDefault();
          return album != null && album.Photos != null && album.Photos.Description != null;
     }
}

Then call it with the list

List<Album> albums;

if(!albums.IsLastPhotoNotNull()){
    //...do other actions
}
brainless coder
  • 6,310
  • 1
  • 20
  • 36
1

Shorter, no. But more efficient, yes.

You are calling the Last() method multiple times. That could harm performance if there are for example database actions involved in that call.

Pull the method outside the if:

var last = albums.Last();
if (last != null 
  && last.Photos != null 
  && last.Photos.Description != null)
{ //action }
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325