C#C
C#3y ago
SWEETPONY

✅ How to automatically check for null?

I have following code:

public IActionResult Put(                                              
    Guid id,                                                           
    UpdateItemDto updateItemDto)                                       
{                                                                      
    var existingItem = Items                                           
        .FirstOrDefault(item => item.Id == id);                        
                                                                       
    var updatedItem = existingItem with                                
    {                                                                  
        Name = updateItemDto.Name,                                     
        Description = updateItemDto.Description,                       
        Price = updateItemDto.Price                                    
    };                                                                 
                                                                       
    var index = Items.FindIndex(existingItem => existingItem.Id == id);
    Items[index] = updatedItem;                                        
                                                                       
    return NoContent();                                                
}                                                                      


existingItem can be null so I will have NRE in this line var updatedItem = existingItem with.

yes, we can solve this issue by checking existingItem for null but I don't want to do this every time, code looks much better without any checks so how to avoid this?
Was this page helpful?