Using nullable types and safe casting (as
doesn't throw exceptions):
_logger.LogInformation("Wrote file at {0}", (streamWriter.BaseStream as FileStream)?.Name);
?
only accesses the property if the result of the expression on the left is not null
, otherwise it returns (evaluates to) null
(it's like it's equivalent to E is T ? (T)(E) : (T)null
).
If you wanted, you could check the cast result for null
like this:
var fs = streamWriter.BaseStream as FileStream;
if (fs != null)
{
_logger.LogInformation("Wrote file at {0}", fs.Name);
}
But that's more code than you need. The more modern way to write the above example with C# 7+ is to use the is
operator:
if (streamWriter.BaseStream is FileStream fs)
{
_logger.LogInformation("Wrote report file at {0}", fs.Name);
}
This has the added benefit that the log call doesn't happen at all, if the cast could not be performed, because actually fs
is never null
when using is
. The entire is
expression evaluates to either true or false, but never null
.