I have the following code Try it here
using System;
using System.Diagnostics.CodeAnalysis;
public class Base{
protected Base(){
Initialize();
}
protected virtual void Initialize(){}
}
public class Derived : Base{
public string _someString;
public Derived() : base(){
}
[MemberNotNull(nameof(_someString))]
protected override void Initialize(){
_someString = "Test";
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
}
}
I'm still getting the warning
/home/Program.cs(16,9): warning CS8618: Non-nullable field '_someString' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. [/home/home.csproj]
Now clearly this field will be fully initialized. However the compiler doesn't realise it. Is there a way to make it understand?
The motivation for this is that Derived is a generated partial class I want the extra members to be automatically initialized. If I just call "Initialize()" directly in the Derived constructor, the warnings disappear, but I want to avoid this step.
When a virtual method is called, the actual type that executes the method is not selected until run time.This kind of hints that Roslyn can't know what would happen.