RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.62k stars 1.23k forks source link

Warning fix using MemberNullAttribute causes accessibility level error. #4763

Closed kvansaders closed 3 months ago

kvansaders commented 5 months ago
          > I think a better solution is to generate
 public string BaseUrl
 {
     get { return _baseUrl; }
     [System.Diagnostics.CodeAnalysis.MemberNotNull(nameof(_baseUrl))]
     set
     {
         _baseUrl = value;
         if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/"))
             _baseUrl += '/';
     }
 }

To let the compiler null analysis know that the property setter sets the field _baseUrl.

In my netstandard2.0 project, this gives: 'MemberNotNullAttribute' is inaccessible due to its protection level.

Originally posted by @kvansaders in https://github.com/RicoSuter/NSwag/issues/4704#issuecomment-1927882073

Vogel612 commented 5 months ago

I'm seeing the same issue as the other commenter on that issue, where the build completely breaks with the following error message:

Error   CS0234  The type or namespace name 'MemberNotNullAttribute' does not exist in the namespace 'System.Diagnostics.CodeAnalysis' (are you missing an assembly reference?)  

as it is, 14.0.3 breaks netstandard compat from what I can tell

Wholteza commented 5 months ago

I'm seeing the same issue as well, trying to use the generated C# client in a net472 project. Downgrading to 14.0.2 removed the attribute from the generated class. That works as a workaround for me at the moment.

ImoutoChan commented 5 months ago

The same issue on my side, MemberNotNull shouldn't be emitted when targeting netstandard2.0

nessuarez commented 5 months ago

The same issue for targeting WinX86 runtime in a .Net framework 4.5.2 project

jstun commented 5 months ago

The same issue on my side as well. Caused by NSwag toolchain v14.0.3.0.

melucas commented 4 months ago

The same issue with NSwag v14.0.3.0 for a .Net 4.8 project.

jochenwezel commented 3 months ago

The feature System.Diagnostics.CodeAnalysis.MemberNotNull introduced with .NET 5 as MS documentation declares at https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.membernotnullattribute?view=net-8.0

So, the code line

            [System.Diagnostics.CodeAnalysis.MemberNotNull(nameof(_baseUrl))]

should be as follows to solve the compilation error

#if NET5_0_OR_GREATER
            [System.Diagnostics.CodeAnalysis.MemberNotNull(nameof(_baseUrl))]
#endif
rwb196884 commented 3 months ago

I need to multi-target net40 and this makes 14 unusable, have to use 13.

jochenwezel commented 3 months ago

If you render the code as provided into the generated document, you don't need to multi-target your solution itself. Just the generated output has to provide the 2 additional lines for compiler directives

Vogel612 commented 3 months ago

Forward duplicated by #4833, fixed since 14.0.6