5

Im getting the warning "Non-nullable event 'SomeEvent' must contain a non-null value when exiting constructor. Consider declaring the event as nullable."

Here's a very simplified version of my code which replicates the exact same problem. What am I missing here? Does this have anything to do with .Net 6?

namespace ConsoleApp3
{
    public delegate void SomeDelegate(object sender, EventArgs args);

    public class NewClass
    {
        public NewClass(string name)
        {
            this.name = name;

        }

        public string name { get; set; }

        public event SomeDelegate SomeEvent;
    }
}
ruwenzori
  • 61
  • 1
  • 3
  • Not near my development machine but I usually declare my events like this: `public event SomeDelegate SomeEvent = delegate { };` to prevent it from being null – Fixation Oct 22 '21 at 12:05
  • 2
    `public event SomeDelegate? SomeEvent;` should fix that warning, make it `nullable`. – Trevor Oct 22 '21 at 12:06
  • 1
    As @zaggler said, but when you invoke the event don't forget to do use it like this `SomeEvent?.Invoke(...);` – DavidG Oct 22 '21 at 12:08
  • all 3 fixed the problem, thanks. obviously i should expand my knowledge on delegates and events, but it weirded me out that it doesn't happen on .net 5, but only on .net 6. – ruwenzori Oct 22 '21 at 12:11
  • 1
    It's only happening because you have nullable reference types enabled for the project. – DavidG Oct 22 '21 at 12:11
  • 1
    @DavidG is correct, I think it's enabled by default as well. – Trevor Oct 22 '21 at 12:13
  • just checked the .csproj file and yeah, that's the issue. – ruwenzori Oct 22 '21 at 12:17

1 Answers1

11

I know I'm late to the party, but Google sent me here, and the only responses were unsatisfactory. I came upon another answer on StackOverflow that felt a lot better, and you can get a good explanation there.

tl;dr just make the event nullable, because that's what it actually is:

public event SomeDelegate? SomeEvent;  
zfrank
  • 388
  • 2
  • 6
  • Language syntax weirdness (this is what had me messed up): The question mark goes after the "type" declaration. Normally, the "type" is a single word near the beginning of the declaration (e.g., the word `string` in `public string? myString;`. But events are special. The "type" is two words: the keyword `event` followed by the delegate name. So, the question mark goes after the delegate name. – Bob.at.Indigo.Health Feb 15 '23 at 01:08