Please god tell me I've been doing this wrong forever.


  • Discourse touched me in a no-no place

    Alright. I'm going to prefix this by saying that never has anybody called me out on this in a code review and indeed it's the only way I've seen it done in any codebase I work on. But every time I write it, I feel like I'm violating some fundamental law of the universe (the one that says "THOU SHALT NOT TOSTRING A FUCKING NUMBER AND THEN PARSE IT AS A NUMBER")

    So here's the deal. I have a DataSet. Or an ExecuteScalar return. Or whatever. It's a fucking database int object. I want it as a real integer so I can actually do shit with it.

     Soooo...

      Int32 i = Int32.Parse(stupid.ToString());

     I know I should JFGI but consider this my confession.

     

     

    And if on the off chance I'm actually doing this CORRECTLY, why the fuck haven't the people responsible been strung up yet?

     

     



  • Convert.ToInt32(any object, string, char, int, ...)



  • int i = (int)reader["intcolumn"];



    Make sure the column isn't nullable.


  • Discourse touched me in a no-no place

    @XIU said:

    Convert.ToInt32(any object, string, char, int, ...)
     

    ... Shit.

     

    Although I get this nagging feeling that it does the same hideous thing as above internally. At least it's shorter.



  • @Weng said:

    @XIU said:

    Convert.ToInt32(any object, string, char, int, ...)
     

    ... Shit.

     

    Although I get this nagging feeling that it does the same hideous thing as above internally. At least it's shorter.

    It does ((IConvertible) value).ToInt32(null). Which is a no-op if value is already an Int32.



  • Since the original value is already some kind of integer, isn't it in this case simply possible to do:

    [code]Int32 i = (Int32) stupid;[/code]

    ?



  •  As said before, you may as well just use Convert.ToInt32 instead of converting it to a string and then back to an integer.  Saves you a little conversion, but the end result is the same.



  • Another option to use with SqlDataReader, which avoids casts and performs somewhat better when selecting many rows:

    SqlDataReader reader = someSqlCommand.ExecuteReader();
    if (reader.Read())
    {
      Int32 columnOrdinal = reader.GetOrdinal("Column");
      do
      {
        Int32 columnValue = reader.GetInt32(columnOrdinal);
        // Do something with columnValue
      }
      while (reader.Read());
    }

Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.