Do not use the default value for double

Using C # in ASP.NET, I want to take the result of two text fields, add them when I click the button, and display the result. However, if one or both fields are empty, I do not want any result to be shown.

At the moment, I get 0 as the result if both fields are empty. I am sure this is because the two input numbers (doubles) are assigned the default value of 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);
    }
+5
source share
4 answers

null "empty". , . Nullable<double>, double? .

, , null NullReferenceException, double 0, .

+11

Double?, .. nullable Double, null, , , .

+4

, . .

string one = txt1.Text;  
string two = txt2.Text;

string result = (string.IsNullOrEmpty(one) || string.IsNullOrEmpty(two))
                 ?string.Empty
                 :double.Parse(one) + double.Parse(two);
+2

if:

    if (operand1 != 0) { // do something.. }
    else { // do something.. }

.

: https://www.dropbox.com/s/snvonqubqpkue99/Form1.cs?dl=0

0
source

All Articles