codecentric / net_automatic_interface

.Net Source Generator for Automatic Interfaces
MIT License
62 stars 14 forks source link

Boolean parameters with non-null defaults throw CS0103 #18

Closed eobeda closed 9 months ago

eobeda commented 1 year ago

Microsoft Visual Studio Enterprise 2022 (64-bit) - Current Version 17.6.4 AutomaticInterface: 1.6.0

Severity Code Description Project
Error CS0103 The name 'False' does not exist in the current context AutomaticInterface-CS0103

Method with non-null defaults on Boolean parameters throw CS0103 error. Sample method call:

   public async Task<Stream?> GetFinalDocumentsByIDFails(
                         string agreementID, 
                         string docType, 
                         bool amt = false , 
                         bool? attachSupportingDocuments = true, 
                         CancellationToken cancellationToken = default)
        {
            await Task.Delay(100);
            return default(Stream?);

        }

Reason: The case of the default value is converted to True or False instead of true or false in the GetMethodSignature method. https://learn.microsoft.com/en-us/dotnet/api/system.boolean?view=net-7.0#converting-to-and-from-boolean-values

Fix: Add an additional case to the swtich statement: bool => $" = {Convert.ToString(x.ExplicitDefaultValue, CultureInfo.InvariantCulture).ToLowerInvariant()}",

AutomaticInterface.cs method "GetMethodSignature" with the fix applied:

 private static string GetMethodSignature(IParameterSymbol x)
    {
        if (!x.HasExplicitDefaultValue) return $"{x.Type.ToDisplayString()} {x.Name}";

        string optionalValue = x.ExplicitDefaultValue switch
        {
            string => $" = \"{x.ExplicitDefaultValue}\"",
            bool => $" = {Convert.ToString(x.ExplicitDefaultValue, CultureInfo.InvariantCulture).ToLowerInvariant()}",
            // struct
            null when x.Type.IsValueType => $" = default({x.Type})",
            null => " = null",
            _ => $" = {x.ExplicitDefaultValue}"
        };
        return $"{x.Type.ToDisplayString()} {x.Name}{optionalValue}";
    }
ChristianSauer commented 9 months ago

Should be fixed in 2.0.0

awasilik commented 9 months ago

@ChristianSauer the issue came back in 2.0.1

image