2

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.

20
  • 2
    Doesn't this produce another warning about calling virtual members in a ctor? => learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/… Commented Oct 17, 2024 at 9:11
  • 2
    @Fildor neither in the above link nor my local system... However your link contains an interesting point: 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. Commented Oct 17, 2024 at 9:39
  • 2
    And I am sure I had a resource with some alternatives to fix that ... but I can't seem to find it ... Commented Oct 17, 2024 at 9:46
  • 2
    It's hard to say without knowing exactly what your generator is doing, but suggestions would be: get the generator to initialise new fields in line, generate the call to initialise in the derived constructor. Suppressing the warning(s) and/or using the null-forgiving operator both raise the risk of later changes causing problems, but as it's generated code that is less of an issue Commented Oct 17, 2024 at 9:46
  • 1
    ^^ Main takeaway was (citation) "Such virtual method, in fact, should be a pure function that returns some value and doesn't depend on the stateof the derived type. If this is the case, make such function static (since it is pure) and pass its return value to the base type as a parameter to protected constructor.". Commented Oct 17, 2024 at 10:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.