Home > Back-end >  How to resolve a CS8602(Dereference of a possibly null reference) when redirecting on null?
How to resolve a CS8602(Dereference of a possibly null reference) when redirecting on null?

Time:06-03

I have the following code:

    GetBenefitById_Result? objBenefit = _db.GetBenefitById(this.BenefitId).FirstOrDefault();
    if (objBenefit == null)
        Response.Redirect(URLConstants.BENEFIT_LIST);

    lblName.Text = objBenefit.Name; //This gives me the error CS8602.

When I build this code, I get the warning "Dereference of a possibly null reference". I know that what is happening is that the compiler is trying to protect me from trying to access the variable Name if objBenefit is null, but how do I tell the compiler that I am redirecting on null, so don't check this?

CodePudding user response:

You could try:

   if (objBenefit == null) {
        Response.Redirect(URLConstants.BENEFIT_LIST);
   }
   else
   {
      lblName.Text = objBenefit.Name;
   }

CodePudding user response:

If you know the value won't be null, you can use the null-forgiving operator (!):

if (objBenefit == null)
        Response.Redirect(URLConstants.BENEFIT_LIST);

    lblName.Text = objBenefit!.Name;
  • Related