tags:

views:

113

answers:

4

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?

+2  A: 

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
+3  A: 

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
A: 
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
Dont catch Exception. It silently masks other kinds of exceptions that may have occured.
Andrew Keith
yuck! `TryParse()` was added to prevent writing this sort of code, and using TryParse is far, far better than swallowing all exceptions!
Robert Paulson
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
A: 

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

return Int32.TryParse(Request["amount"], out i)) ? (int?)i : (int?)null;
abatishchev