diff --git a/Speckle.InterfaceGenerator.Tests/MethodGenerationTests.cs b/Speckle.InterfaceGenerator.Tests/MethodGenerationTests.cs index a860f1f..36ea1e7 100644 --- a/Speckle.InterfaceGenerator.Tests/MethodGenerationTests.cs +++ b/Speckle.InterfaceGenerator.Tests/MethodGenerationTests.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; using System.Text; using FluentAssertions; using Xunit; @@ -159,6 +160,36 @@ public class MethodGenerationTests var _ = _sut.StringMethod(); } + [Fact] + public void StringMethodNullable_IsImplemented() + { + var method = + typeof(IMethodsTestService).GetMethod(nameof(MethodsTestService.StringMethodNullable)) + ?? throw new InvalidOperationException(); + + method.Should().NotBeNull(); + method.ReturnType.Should().Be(typeof(string)); + IsNullable(method.ReturnType).Should().BeTrue(); + + var parameters = method.GetParameters(); + parameters.Should().BeEmpty(); + + var _ = _sut.StringMethod(); + } + + private static bool IsNullable(Type type) + { + var nullableContextAttribute = type.GetCustomAttribute(); + + // NullableContextAttribute exists and has a flag indicating nullable annotations + if (nullableContextAttribute != null && nullableContextAttribute.Flag == 1) + { + return true; + } + + return false; + } + [Fact] public void GenericVoidMethod_IsImplemented() { @@ -312,6 +343,11 @@ internal class MethodsTestService : IMethodsTestService return string.Empty; } + public string? StringMethodNullable() + { + return null; + } + public void GenericVoidMethod() { } public void GenericVoidMethodWithGenericParam(TX a) { } diff --git a/Speckle.InterfaceGenerator/AutoInterfaceGenerator.cs b/Speckle.InterfaceGenerator/AutoInterfaceGenerator.cs index 4c2d29d..40771e4 100644 --- a/Speckle.InterfaceGenerator/AutoInterfaceGenerator.cs +++ b/Speckle.InterfaceGenerator/AutoInterfaceGenerator.cs @@ -176,10 +176,8 @@ public class AutoInterfaceGenerator : ISourceGenerator var visibilityModifier = InferVisibilityModifier(implTypeSymbol, attributeData); //https://stackoverflow.com/questions/55492214/the-annotation-for-nullable-reference-types-should-only-be-used-in-code-within-a fix for nullable - if (implTypeSymbol.NullableAnnotation == NullableAnnotation.Annotated) - { - codeWriter.WriteLine("#nullable enable"); - } + + codeWriter.WriteLine("#nullable enable"); codeWriter.WriteLine("namespace {0}", namespaceName); codeWriter.WriteLine("{"); @@ -198,10 +196,7 @@ public class AutoInterfaceGenerator : ISourceGenerator --codeWriter.Indent; codeWriter.WriteLine("}"); - if (implTypeSymbol.NullableAnnotation == NullableAnnotation.Annotated) - { - codeWriter.WriteLine("#nullable restore"); - } + codeWriter.WriteLine("#nullable restore"); codeWriter.Flush(); stream.Seek(0, SeekOrigin.Begin);