Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dont' use default value for double

Using C# in ASP.NET, I want to take the result of two text fields, add them when a button is pressed, and display the result. However, if one or both of the fields are empty, I don't want any result shown.

Right now I keep getting 0 as the result if both fields are empty. I'm pretty sure this is because the two input numbers (doubles) are being assigned a default 0. How can I check for empty fields?

This is my method in my controller.

    [HttpPost]
    public ActionResult French(FrenchModel model, string returnUrl)
    {

        switch (model.operation)
        {
            case 1:
                model.result = model.numberOne + model.numberTwo;
                break;
            case 2:
                model.result = model.numberOne - model.numberTwo;
                break;
            case 3:
                model.result = model.numberOne * model.numberTwo;
                break;
            case 4:
                model.result = model.numberOne / model.numberTwo;
                break;
        }


        return View(model);
    }
like image 311
Bill Avatar asked May 26 '11 21:05

Bill


People also ask

How do you set a double to null?

As an object, it can be assigned a null reference. But "double" (with a lowercase 'd') is a primitive type, so it cannot be assigned a null reference. The analogous primitive value is simply zero.

How do you handle a double null in C#?

double is a value type, which means it always needs to have a value. Reference types are the ones which can have null reference. So, you need to use a "magic" value for the double to indicate it's not set (0.0 is the default when youd eclare a double variable, so if that value's ok, use it or some of your own.


2 Answers

Doubles are value types and thus cannot be assigned to null or "empty". If you want this capability, try using a nullable double. Either Nullable<double> or double? should work.

Be aware, using a nullable value type you will need to check it for null before you use it or risk a NullReferenceException whereas double defaults to 0 if unassigned.

like image 151
Adam Price Avatar answered Sep 17 '22 20:09

Adam Price


Use Double? ie nullable Double, its default value is null and you'll assign a value only if textbox is not empty and you can parse it.

like image 42
AD.Net Avatar answered Sep 18 '22 20:09

AD.Net