Home > Enterprise >  CS8625 Cannot convert null literal to non-nullable reference type warning for API call that may expe
CS8625 Cannot convert null literal to non-nullable reference type warning for API call that may expe

Time:09-05

I am cleaning all null reference warnings from my C# code and have a warning when calling Win32 API methods.

Per the method documentation I can pass in an empty string so could resolve the warning with string.Empty.

However, for the general case how can we eliminate this warning and allow nulls - what about other API methods that really would expect a null not just empty string?

Is it simply a case of declaring the parameter as string? machineName? My days of C and string buffer overruns makes one paranoid so pointers appreciated (no pun intended!).

[DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
    static extern IntPtr OpenSCManager(string machineName, string databaseName, ScmAccessRights dwDesiredAccess);

// Calling code that is generating the CS8625 warning - we could use string.Empty, but how
// would we in general allow a null to be passed to a Win32 dll call?
var scm = OpenSCManager(null, null, rights);
if (scm == IntPtr.Zero)
 throw new ApplicationException("Could not connect to service control manager.");

CodePudding user response:

If method accepts nulls and you have control over the signature - just modify it:

[DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr OpenSCManager(string? machineName, string? databaseName, ScmAccessRights dwDesiredAccess);

Otherwise you can use the "shut up compiler, I'm smarter" (though based on my experience the second part not always true so in general I would recommend trying to avoid it) operator aka ! (null-forgiving) operator on the call site:

var scm = OpenSCManager(null!, null!, rights); 

Also check out the docs regarding nullable reference types.

  • Related