Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to better initialize nullable type from non-nullable?

Tags:

c#

.net

nullable

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?

like image 566
abatishchev Avatar asked Apr 28 '26 07:04

abatishchev


2 Answers

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);
like image 197
Marc Gravell Avatar answered Apr 30 '26 20:04

Marc Gravell


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;
    }
}
like image 37
Randolpho Avatar answered Apr 30 '26 20:04

Randolpho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!