3

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433

5 Answers5

10

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);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

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;
    }
}
Randolpho
  • 55,384
  • 17
  • 145
  • 179
1

I like little bit rewrite of Randolpho's and Marc's code:

return Int32.TryParse(Request["amount"], out i)) ? (int?)i : (int?)null;
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

Unless your caller demands a Nullable<T>, I'd suggest using a type like:

struct MaybeValid<T>
{
    public bool IsValid;
    public T Value;
}

That would allow:

Public MaybeValid<int> Amount
{
    Amount.Value = Int32.TryParse(out Amount.IsValid);
}

With Int32, the extra typecasting effort probably isn't too much of an issue, but with larger types, it could be more significant.

supercat
  • 77,689
  • 9
  • 166
  • 211
-5
public int? Amount
{
    get
    {
         try 
         {
               return Int.Parse(Request["amount"]);
         }
          catch (exception e) 
         { 
               return null;
         }
     }
{

Performance is not really going to change, but if you really want to optimize, then you need to think about what is most common, if the values are almost always valid ints, then my approach is likely best, if not then your approach is best.

Paul Creasey
  • 28,321
  • 10
  • 54
  • 90
  • Dont catch Exception. It silently masks other kinds of exceptions that may have occured. – Andrew Keith Dec 14 '09 at 22:50
  • 6
    yuck! `TryParse()` was added to prevent writing this sort of code, and using TryParse is far, far better than swallowing all exceptions! – Robert Paulson Dec 14 '09 at 22:51
  • 2
    http://stackoverflow.com/questions/150114/parsing-performance-if-tryparse-try-catch this post says i'm wrong, even when there are no failures, so point taken! – Paul Creasey Dec 15 '09 at 08:04