开发者

Dont' use default value for double

Using C# in ASP.NET,开发者_C百科 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);
    }


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.


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.


Here's one way to determine if one or both of the fields are empty. Refactor as you need with your particular variables.

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

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


You can use if statements:

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

You can also do this for the second operand

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜