Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a nullable reference type to a non-nullable reference type, less verbosely

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;
like image 293
TheColonel26 Avatar asked Jul 25 '19 13:07

TheColonel26


1 Answers

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");
like image 187
Jonathon Chase Avatar answered Oct 01 '22 09:10

Jonathon Chase