"Non-nullable event must contain a non-null value when exiting constructor"
Asked Answered
A

2

9

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;
    }
}
Anticipant answered 22/10, 2021 at 12:1 Comment(7)
Not near my development machine but I usually declare my events like this: public event SomeDelegate SomeEvent = delegate { }; to prevent it from being nullCorrade
public event SomeDelegate? SomeEvent; should fix that warning, make it nullable.Towrey
As @zaggler said, but when you invoke the event don't forget to do use it like this SomeEvent?.Invoke(...);Ravel
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.Anticipant
It's only happening because you have nullable reference types enabled for the project.Ravel
@Ravel is correct, I think it's enabled by default as well.Towrey
just checked the .csproj file and yeah, that's the issue.Anticipant
B
14

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;  
Belia answered 3/2, 2022 at 1:2 Comment(1)
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.Educative
A
-1

Initialize the property to the default.

public string name { get; set; } = default!;
Almandine answered 7/2 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.