Is there a way I can convert a nullable reference type to non-nullable reference type in the below example less verbosely?
This would be for when the nullable reference flag for the compiler is enabled.
When the nullable reference type is null
, I would like it to throw an exception.
Assembly? EntryAssemblyNullable = Assembly.GetEntryAssembly();
if (EntryAssemblyNullable is null)
{
throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");
}
Assembly EntryAssembly = EntryAssemblyNullable;
var LocationNullable = Path.GetDirectoryName(EntryAssembly.Location);
if (LocationNullable is null)
{
throw new Exception("The CLR method of Assembly.GetEntryAssembly().Location returned null");
}
string ExecutableLocationPath = LocationNullable;
You can use throw expressions with the null coalescing operator.
Assembly EntryAssembly = Assembly.GetEntryAssembly() ?? throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With