Home > database >  Possible Null reference return
Possible Null reference return

Time:10-19

sorry if this is a basic question, but I was wondering the following.

I've been following MS guides to create some Razor pages, but I get the warning in the title on the following case. I have this simple class with a required attribute and a non-required one.

    public class Deck
    {
        public int ID { get; set; }
        public string Name { get; set; } = String.Empty;
        public string? Link { get; set; } = String.Empty;
    }

and on the Create page (scaffolded) I have this form:

       <form method="post">
            <div asp-validation-summary="ModelOnly" ></div>
            <div >
                <label asp-for="Deck.Name" ></label>
                <input asp-for="Deck.Name"  />
                <span asp-validation-for="Deck.Name" ></span>
            </div>
            <div >
                <label asp-for="Deck.Link" ></label>
                <input asp-for="Deck.Link"  />
                <span asp-validation-for="Deck.Link" ></span>
            </div>
            <div >
                <input type="submit" value="Create"  />
            </div>
        </form>

But on the Post method, when trying to update the model, it says that Link may be null (as shown in the image below). I was wondering if I'm missing something or should have done anything different. Is this a problem? If not, how can I suppress this message?

Thank you.

enter image description here

CodePudding user response:

The warning that you're seeing is just letting you know that the string Link in Deck was defined as a nullable string, which is what the question mark means after the type. To get this to go away, you need to explicitly check that Link is not null or has a value.

The easiest way to do so would be to do this

d => d.Link ?? ""

which would replace a null version Link with an empty string. This may or may not be what you want so just keep in mind that you don't need to change anything for this to work. As long as you don't try and use Link when its null you won't have any issues.

The double question mark operator is called a Null-coalescing operator. What it does it check the left side to see if its null, and if it is it uses the right side instead.

  • Related