Search code examples
c#.net-core-3.1

How is the Assembly.Load(Assembly) never null?


In NET Core 3.1

https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load?view=netcore-3.1#System_Reflection_Assembly_Load_System_Reflection_AssemblyName_

How is the return value of Assembly.Load(Assembly) never null? The code hint I receive is that the expression (Assembly.Load(Assembly) != null) is always true. Is Assembly a reference type?

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

enter image description here


Solution

  • .NET Core:

    That's because of this line in the source code, which effectively tells the compiler this value is not null. See documentation on the static code analysis here.

    return retAssembly!;
    

    So you'll get a non-null value or an exception.

    .NET Framework:

    That's because the source code has a contract:

    public static Assembly Load(AssemblyName assemblyRef)
    {
        Contract.Ensures(Contract.Result<Assembly>() != null);
        //More code
    }
    

    So you will either get a non-null return value, or an exception.