I have got a method in which I 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
This works because
ifis using Short-circuit evaluation: theproducts!=0condition is only evaluated ifproduct.HasValueis 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 theGetValueOrDefault()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.