C
C#10mo ago
TOKYODRIFT!

✅ 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();
}
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?
9 Replies
ero
ero10mo ago
if it can be null, then you have to check for null there's just no way around that and what if it doesn't exist after all?
TOKYODRIFT!
TOKYODRIFT!10mo ago
it is bad Smadge
ero
ero10mo ago
how? you have to handle it separately anyway
if (existingItem is null)
return NotFound();
if (existingItem is null)
return NotFound();
TOKYODRIFT!
TOKYODRIFT!10mo ago
I know but.. it's a little bit annoying to do
Thinker
Thinker10mo ago
Check for null, there is literally no good reason not to How would you do this otherwise?
ero
ero10mo ago
you could do
if (Items.FirstOrDefault(item => item.Id == id) is not { } existingItem)
return NotFound();
if (Items.FirstOrDefault(item => item.Id == id) is not { } existingItem)
return NotFound();
i guess
TOKYODRIFT!
TOKYODRIFT!10mo ago
I want the null check to be done automatically or all errors to be logged automatically so that I don't have to do it all myself but this looks good
ero
ero10mo ago
there's no such thing as an "automatic null check" you could call only .First(), but that will throw a different exception if the item doesn't exist
TOKYODRIFT!
TOKYODRIFT!10mo ago
sigh.. okay, thanks for helping me