Inform resharper that an out variable will only be null if the function returns false;

99 views Asked by At

I have the following function that follows the TryGet pattern with an out param that if null will return false, if it is not null it will return true

public bool TryGetFileFormat(string extension, [CanBeNull] out IFileFormat fileFormatter)
{
    fileFormatter = Plugins?.FirstOrDefault(plugin => plugin?.FileExtension != null && plugin.FileExtension.Equals(extension));
    return (fileFormatter != null);
}

I then call the function with the following code:

IFileFormat fileFormatPlugin;
if (_pluginLoader.TryGetFileFormat(extension, out fileFormatPlugin))
{
    fileFormatPlugin.DoStuff();

Resharper then warns me that fileFormatPlugin could be null. How can I tell resharper that it will only be null if the function returns false?

Edit I suspect I can handle this with ContractAnnotation somehow, but unsure the syntax.

1

There are 1 answers

0
rollsch On BEST ANSWER

The following contract annotation causes resharper to only warn about null reference if you use the value when the function has returned false

[ContractAnnotation("fileFormatter : null => false")]
public bool TryGetFileFormat(string extension, [CanBeNull]out IFileFormat fileFormatter){
    fileFormatter = Plugins?.FirstOrDefault(plugin => plugin?.FileExtension != null && plugin.FileExtension.Equals(extension));
    return (fileFormatter != null);
}