开发者

Query Related to if conditional operator

I have got a method in which I开发者_C百科 have done something like:

int? products= formvalues["number"] == "" ? (int?)null : Convert.ToInt32(formvalues["number"]);
if(products.HasValue)
{ 
    // do some calulation
}

The Issue is I dont want to do calculation if product has 0 or null value else do calculation, How can I do that as the current logic avoid calculation when its null but it doesnt avoid when the product has 0 value


if(products.HasValue && products !=0)
{ 
    // do some calculation
}

This works because if is using Short-circuit evaluation: the products!=0 condition is only evaluated if product.HasValue is true.

Edit:

This particular if statement also would work without short-circuit evaluation since null!=0 - short-circuit evluation is useful if you have to access a member of a variable by prefixing it with a null check in the if statement.

Also as pointed out Nullable<T> provides the GetValueOrDefault() method to do the same check as above (@Bradley got my +1) - in this case it is a matter of personal preference /readability which to use.

Also the real answer your question should be to use Int32.TryParse() instead of "manually" trying to validate the input.


Using your original code, you could write:

if (products.GetValueOrDefault() != 0)
{
    // do some calulation
}

GetValueOrDefault will return 0 if products is null.

However, I would probably write it as follow (to avoid a potential FormatException thrown by Convert.ToInt32 failing to parse user-submitted data):

int products;
if (int.TryParse(formvalues["number"], out products) && products != 0)
{
    // do some calculation
}


Get rid of the nullable int and perform a safer conversion:

 int products;
 bool parsed = Int32.TryParse(formvalues["number"], out products);
 if (parsed && products != 0)
 {

 }


Try this

if (products.HasValue && products.Value != 0)
{
    // do some calulation
}


I prefer this if((products ?? 0) != 0){}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜