Search code examples
c#parametersvisual-studio-codeout

C# error about missing "out" parameter, but the code works fine


I have a C# project that contains a method that looks something like this:

bool TheMethod(Type arg, out Type output)

And then it's called later on in the file, it looks something like this, with only one argument:

if (TheMethod(someArgument))

And VS Code reports this error:

There is no argument given that corresponds to the required formal parameter 'output' of 'TheMethod(Type, out Type)' (CS7036) [Managed]

Despite this error, the code compiles and runs fine. What's going on? Is this a problem with code validation? Is the out parameter required in some cases, but not others? Should I edit the code so that it outputs to a local field, even if I won't ever use it?

The actual code can be found here: https://github.com/godotengine/godot/blob/master/modules/mono/glue/Managed/Files/MarshalUtils.cs#L156


Solution

  • Assuming you mean the method:

    static bool GenericIDictionaryIsAssignableFromType(Type type, out Type keyType, out Type valueType)
    

    and the call to the method:

    #if DEBUG
                if (!GenericIDictionaryIsAssignableFromType(dictionary.GetType()))
                    throw new InvalidOperationException("The type does not implement IDictionary<,>");
    #endif
    

    Then the behavior you are seeing is likely linked to the existence of the preprocessor directives (#if/#endif). If you're compiling the code locally in DEBUG mode,

    Debug Compiler Setting

    the code will throw a compiler error of the sort you're seeing. However, if you compile/run in RELEASE mode (which may be how your CI/CD and/or other test environments may be configured) the code will not have any errors (as the #if/#endif excludes the relevant lines of code from the file before the compiler sees them) and it will run as expected.