2

Convert.ToInt16(row["INT"] as Int16?); returns 0 and (Int16)row["INT"]; throws an exception Specified cast is not valid.

    private DataTable GetTableWithValue()
    {

        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { 
            new DataColumn("INT", typeof(Int32)),
            new DataColumn("STRING", typeof(string )),
            new DataColumn("DATETIME", typeof(DateTime )),
            new DataColumn("BOOLEAN", typeof(bool)),
        });

        dt.Rows.Add(dt.NewRow());

        dt.Rows[0][0] = 10;
        dt.Rows[0][1] = "Babu";
        dt.Rows[0][2] = DateTime.Now;
        dt.Rows[0][3] = true;
        return dt;
    }


        dt = GetTableWithValue();
        row = dt.Rows[0];


        int? INT = (row["INT"] as int?); //10
        Int16? INT16 = Convert.ToInt16(row["INT"] as Int16?); //0
        Int16 = (Int16)row["INT"]; //Specified cast is not valid. 
Babu Kumarasamy
  • 329
  • 2
  • 6
  • 15
  • if value of row["INT"] is null then (Int16)row["INT"] code will not handle. Convert.ToInt16() takes argument as an object and will not throw null expcetion – LifeOfPi Sep 12 '16 at 11:11
  • 1
    Does the last line incorrect ? Int16 = (Int16)row["INT"]; //Specified cast is not valid. i think it should be INT16 = (Int16)row["INT"]; //Specified cast is not valid. – Maxim Kitsenko Sep 12 '16 at 11:16
  • if you had done `Convert.ToInt16(row["INT"] as int?)` or even just `Convert.ToInt16(row["INT"])` your 2nd line would have worked. it is the `as Int16` that is breaking it. – Scott Chamberlain Sep 13 '16 at 05:26

1 Answers1

1

row["INT"] as Int16? returns null when either the provided value within the row is zero, or when the value from the row is not castable to Int16 (for example if the content was "zero"). Convert.ToInt16(null) now returns zero.

However the "direct" cast (Int16) myValue throws an exception when the cast fails. See here for more details

Anyway in your code you´re trying to cast an Nullable<int> to Int16 which is obviously not possible. You can however use the nullables value, which is an int:

Int16 result = ((int?)row["INT"]).Value;

EDIT: A quite better aproach would be to use TryParse which won´t throw an exception if parsing fails but simply returns false:

Int16 result;
if (Int16.TryParse(row["INT"].ToString(), out result))  
{
    // do something with result
}
Community
  • 1
  • 1
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111