C
C#16mo 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();
}
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
ero16mo 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?
SWEETPONY
SWEETPONYOP16mo ago
it is bad Smadge
ero
ero16mo ago
how? you have to handle it separately anyway
if (existingItem is null)
return NotFound();
if (existingItem is null)
return NotFound();
SWEETPONY
SWEETPONYOP16mo ago
I know but.. it's a little bit annoying to do
Thinker
Thinker16mo ago
Check for null, there is literally no good reason not to How would you do this otherwise?
ero
ero16mo 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
SWEETPONY
SWEETPONYOP16mo 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
ero16mo 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
SWEETPONY
SWEETPONYOP16mo ago
sigh.. okay, thanks for helping me
Want results from more Discord servers?
Add your server