dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
18.95k stars 4.02k forks source link

Allow `MemberNotNull` on constructors #71526

Open alrz opened 8 months ago

alrz commented 8 months ago

The current workaround is to define a new property as it is done for BoundExpression.Type in roslyn.

using System.Diagnostics.CodeAnalysis;

new C(1).Value.ToString(); // no warning

class B {
  public B(object? value) => Value = value;
  public object? Value { get; }
}
class C : B {
  [MemberNotNull(nameof(Value))] // currently not allowed 
  public C(object value) : base(value) { }
}

Note the member doesn't actually need to be defined in the base so some constructor could be setting this member and some not.

sharwell commented 8 months ago

This would need to be changed in the runtime before we could do anything here https://github.com/dotnet/runtime/blob/1d5f483fa4344328fb85fd67fc482b70b31e6c4d/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs

alrz commented 8 months ago

Of course, the compiler team needs to show interest to do this before proposing the change to the runtime. This alongside of https://github.com/dotnet/roslyn/issues/43906 and possibly others.