Successfully added
.NET
by Patrik
Safe Logging When Objects Can Be Null
When data is loaded from a list or a database, there is always a chance that nothing is found. If the code still tries to access properties on a missing object, the log statement itself can crash the application.
A simple null check makes the behavior explicit and keeps the log stable:
var item = items.FirstOrDefault(x => x.Id == id);
if (item == null)
{
logger.LogWarning("No item found for Id={Id}", id);
}
else
{
logger.LogInformation(
"Id={Id}, Type={Type}",
item.Id,
item.Type);
}
This version clearly separates the “not found” case from the normal case and produces meaningful log messages for both situations.
When a more compact style is preferred, null operators can be used instead:
logger.LogInformation(
"Id={Id}, Type={Type}",
item?.Id ?? "<unknown>",
item?.Type ?? "<unknown>");
Both approaches prevent runtime errors and ensure that logging remains reliable even when data is incomplete.
logging
null
safety
dotnet
debugging
Referenced in:
Comments