codecentric / net_automatic_interface

.Net Source Generator for Automatic Interfaces
MIT License
60 stars 13 forks source link

Optional Parameters #14

Closed adam-kimmorley-leverage closed 1 year ago

adam-kimmorley-leverage commented 1 year ago

Hi, I love your work, this is an awesome time saver. There seems to be an issue when generating a method with optional parameters, the generated code doesn't have the default values. I'm not sure what I'm doing, when I downloaded the code and ran the tests they all failed, so just going to post the code I got working here... In GeneratorTests.cs I added....

[Fact]
        public async Task WorksWithOptionalParameters()
        {
            var code = @"
using AutomaticInterfaceAttribute;

namespace AutomaticInterfaceExample;

[GenerateAutomaticInterface]
public class DemoClass
{
        public bool TryStartTransaction(
            [CallerFilePath] string file = """",
            [CallerMemberName] string member = """",
            [CallerLineNumber] int line = 0)
        {
return true;
}
}

";

            var expected = @"//--------------------------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// </auto-generated>
//--------------------------------------------------------------------------------------------------

using System.CodeDom.Compiler;
using AutomaticInterfaceAttribute;

namespace AutomaticInterfaceExample
{
    [GeneratedCode(""AutomaticInterface"", """")]
    public partial interface IDemoClass
    {
    bool TryStartTransaction(string file = """", string member = """", int line = 0);        
    }
}
";
            await RunTestAsync(code, expected);
            Assert.True(true); // silence warnings, real test happens in the RunAsync() method
        }

And in AutomaticInterface.cs in te AddMethodsToInterface method I changed line 163 to

.Select(x => $"{x.ToDisplayString()} {x.Name}{(x.IsOptional ? $" = {(x.ExplicitDefaultValue is string ? $@"""{x.ExplicitDefaultValue ?? ""}""" : x.ExplicitDefaultValue?.ToString() ?? "")}" : "")}")

That worked but I have no idea if that's the right way or if it will break something else., hopefully it's helpful

ChristianSauer commented 1 year ago

Ok, that took way longer than I hoped for, but life took a toll. I just uploaded 1.4.x - which should fix this problem. Your idea works, but I needed some more code to handle default and null parameters, which are treated differently by Roslyn.