My objects often has nullable types properties that used as SQL commands parameters.
I initialize them next way:
public int? Amount
{
get
{
int i;
int? amount = null;
if (Int32.TryParse(Request["amount"], out i))
{
amount = i;
}
return amount;
}
}
command.Parameters.Add("@amount").Value = (object)this.Amount ?? DbNull.Value;
How can I rewrite such initialization code to make it shorter or faster?
Firstly, don't do that; you are silently dropping the fact that you can't parse the data! Better to throw an exception in this case, or handle expected scenarios (null, for example).
string val = Request["amount"];
return string.IsNullOrEmpty(val) ? (int?)null : (int?)int.Parse(val);
1) Shorter != faster. Important to note.
2) This will work just as well:
public int? Amount
{
get
{
int i;
if (Int32.TryParse(Request["amount"], out i))
{
return i;
}
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With