How can I create a non-nullable variable when it s initialized in an event

0 votes

This is razor code but I think the same can happen in almost any C# code in an event-driven architecture.

private List<User> Users { get; set; }
protected override async Task OnInitializedAsync()
{
    Users = await Context.Users.Include(u => u.Address).ToListAsync();
}

So the above code will initialize Users before it is ever accessed. However, it puts up a warning that a non-nullable variable is not being initialized.

Is this a case of assigning "default!" to it which is my way of saying don't worry it'll be initialized before it is accessed?

Update: This occurs inside a .razor page in the @code part. So it exists while the HTML is being rendered to pass back to the user's browser. I'm writing this code in an ASP.NET Core Blazor app.

The problem here is the Users object needs to be accessible to all the code in the .razor file. But the code is loaded in the async method. And this method is called part of the .razor file creation, so it needs to be in there.

May 11, 2023 in UI UX Design by vijaytejashwini

edited 4 days ago 89 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP