-2

I have a simple question.

Scenario: Method to update data, when user don't fill the field speed (dt.Row[9]).

//Car.speed is float and dt.row[9] is a object

 float speedo;
 float.TryParse(dt.Row[9].ToString(), out speedo);
 Car.speed = speedo 

or

 Car.speed = dt.Row[9].ToString().Equals(string.Empty) ? 0 : Convert.ToSingle(dt.Row[9])

Considering performance and good code, what is better? Any suggestion?

I know it's not a big deal, but I have many class with many attribute of type float. So it's only to have a code more clean.

Niko
  • 26,516
  • 9
  • 93
  • 110
Icaroo
  • 131
  • 2
  • 8
  • possible duplicate of [Possible to use ?? (the coalesce operator) with DBNull?](http://stackoverflow.com/questions/9436852/possible-to-use-the-coalesce-operator-with-dbnull) – 48klocs Oct 17 '14 at 20:43

1 Answers1

-1

then I look some similar questions , like the Abe's question and change my code to :

 Car.speed = DBNULL.value.Equals(dt.Row[9]) ? 0 : Convert.ToSingle(dt.Row[9])

Later I decide to use the asawyer'method (from the same link) with a new class, like this:

 public  static class   ExtensionDBNull
     {

 public static float DBNullToFloat(this object TheObject, object DefaultValue)
    {

        return DBNull.Value.Equals(TheObject) ? 0 : Convert.ToSingle(TheObject);

        //if (TheObject is DBNull)
        //    return DefaultValue;
        //return Convert.ToSingle(TheObject);

    }
   }

So now I have

    Car.speed = ExtensionDBNull.ObjectToFloat(dt.row[9],0);
Community
  • 1
  • 1
Icaroo
  • 131
  • 2
  • 8