2

I defined the PropertyChangedEventHandler in this way:

public event PropertyChangedEventHandler PropertyChanged;

Since I switched to .NET 7 I get 2 error messages. Once CS8612 (Nullability of reference types in type doesn't match implicitly implemented member.) and CS8618 (Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable.). I don't know how to fix the error.

SomeBody
  • 7,515
  • 2
  • 17
  • 33
Sascha
  • 37
  • 6

1 Answers1

7

TL;DR

Events should be nullable:

public event PropertyChangedEventHandler? PropertyChanged;

Explanation

Event handlers are multicast delegates, basically a linked list. When there are no subscribers to an event, the event delegate is null. That explains why most invocations of an event use the null-conditional operator:

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(...));

When you switched to .NET 7, you must have enabled compile-time checking of nullability.

Nullability of reference types in type doesn't match implicitly implemented member.

The compiler is warning you that the implicit implementation (caused by use of the 'event' keyword) is the nullable type PropertyChangedEventHandler? and this doesn't match your declared type PropertyChangedEventHandler.

Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable.

Since you didn't explicitly say that this property is allowed to be null, then it is not allowed to be null. It has to be initialized with a value when you exit the constructor. For an event, this doesn't make sense - the only way to make it not null is to subscribe, but you are the publisher of the event, not the subscriber.

Julian
  • 5,290
  • 1
  • 17
  • 40
Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62