1

Consider this code within my base class

public MyClass? Input { get; set; }
protected virtual void DoSomething()
{
    Input = new();
}

Now I want to override the method and modify some properties on my Input property.

protected override void DoSomething()
{
    base.DoSomething();

    Input.Name = "Test";
}

Now I get the warning

CS8602 - Dereference of a possibly null reference.

I know I can say that it cannot be null be doing it like this:

Input!.Name = "Test";

But I don't want to do it everytime. Is there a better way to tell the compiler that Input is not null, when the base of the function has already been executed?

Marvin Klein
  • 1,436
  • 10
  • 33
  • 1
    Side note: Considering the fact that the `Input` property has a public set, if you're working in a multithreaded environment you can't even be sure that it will not be null even if you're using it immediately after calling base, without implementing a lock mechanism. – Zohar Peled Jun 26 '23 at 07:42
  • @ZoharPeled There are many cases where the warnings given by NRT are not valid if you have multiple threads manipulating members at at the same time. Providing warnings about this is an explicitly not a goal of NRT. – canton7 Jun 26 '23 at 07:55
  • Thanks for your input. In my case I'm not using a multithreaded environment so the two ansers below are exactly what I'm looking for. – Marvin Klein Jun 26 '23 at 08:11

2 Answers2

4

You want [MemberNotNull(nameof(Input))].

This tells the compiler that the named property will be non-null after the decorated method has executed.

[MemberNotNull(nameof(Input))]
protected virtual void DoSomething()
{
    Input = new();
}

SharpLab

canton7
  • 37,633
  • 3
  • 64
  • 77
4

You could use the MemberNotNull for that.

[MemberNotNull(nameof(Input)]
protected virtual void DoSomething()
{
    Input = new();
}
jraufeisen
  • 3,005
  • 7
  • 27
  • 43