Reputation: 2728
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;
Upvotes: 11
Views: 823
Reputation: 9714
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");
Upvotes: 13