How to assign a nullable object reference to a non-nullable variable?

Viewed 6233

I am using VS2019 and has enabled nullable check semantics in project setting. I am trying to get the executable's path using assembly as below:

        var assembly = Assembly.GetEntryAssembly();
        if (assembly == null)
        {
            throw new Exception("cannot find exe assembly");
        }
        var location = new Uri(assembly.GetName().CodeBase);//doesn't compile.

It says, "assembly" is a [Assembly?] type, while the Uri ctor requires a string, compilation error is:

error CS8602: Dereference of a possibly null reference.

How to fix my code to make it compile? Thanks a lot.

2 Answers

You can use null-forgiving operator ! to tell the compiler that CodeBase can't be null

var location = new Uri(assembly.GetName().CodeBase!);

or use a null-coalescing operator ?? with some default value

var location = new Uri(assembly.GetName().CodeBase ?? string.Empty);

The error

CS8604: Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)'

usually treated as warning, it seems that you've enabled this option in project settings

Your problem is that AssemblyName.CodeBase is nullable: it's of type string?.

You need to add extra code to handle the case where .CodeBase is null (or suppress it with !), e.g:

var codeBase = Assembly.GetEntryAssembly()?.GetName().CodeBase;
if (codeBase == null)
{
    throw new Exception("cannot find exe code base");
}
var location = new Uri(codeBase);

or

var location = new Uri(assembly.GetName().CodeBase!);

The actual warning you get in this case is nothing to do with assembly, it's:

warning CS8604: Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)'.

Source (expand the "Warnings" pane on the lower right). This tells you that the problem is with the string being passed into the Uri constructor, i.e. the string returned from .CodeBase.

Related