0

In if else structure when null arguments are passed to two string variables then it always hit the condition when i have set Var1 != "" && Var2 != "" why ? since nulls are passed to both then why it hits this condition ?

code:

 public ActionResult ShowCalTextBox(String DateFrom, String DateTo) 
        {

           if (DateFrom != "" && DateTo == "") 
            {
                IEnumerable<GetEmpRec_DateResult> EmpRec_DateFrom = DataContext.GetEmpRec_Date(DateFrom, null).ToList();
                ViewBag.Dates = "Records for"+" "+ DateFrom ;
                return View(EmpRec_DateFrom);

            }
            else if (DateFrom == "" && DateTo != "") 
            {
                IEnumerable<GetEmpRec_DateResult> EmpRec_DateTo = DataContext.GetEmpRec_Date(null, DateTo).ToList();
                ViewBag.Dates = "Records for" + " " + DateTo;
                return View(EmpRec_DateTo);
            }
            else if (DateFrom != "" && DateTo != "") 
            {
                IEnumerable<GetEmpRec_DateResult> EmpRec_ByDate = DataContext.GetEmpRec_Date(DateFrom, DateTo).ToList();
                ViewBag.Dates = "Records from" + " " + DateFrom +" "+"to"+" "+DateTo;
                return View(EmpRec_ByDate);
            }
            else if (DateFrom == "" && DateTo == "")
            {
                IEnumerable<GetEmpRec_DateResult> EmpRec_Default = DataContext.GetEmpRec_Date(null, null).ToList();
                ViewBag.Dates = "No date selection";
                return View(EmpRec_Default);
            }

            return View();
        }

it hits this one when i first browse this action or run this action.

else if (DateFrom == "" && DateTo != "")

2
Contributors
1
Reply
12
Views
3 Years
Discussion Span
Last Post by JorgeM
1

Null and "" is not the same.

If you are passing null values then check for nulls.

Try...

 string.IsNullOrEmpty(var1)

Which is the equivalent to...

 ((var1 == null || var1 == string.Empty))

So in your case...

 If (string.IsNullOrEmpty(DateFrom) && string.IsNullOrEmpty(DateTo))
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.