Home > database >  Why does this simple assignment of a bool generate an error
Why does this simple assignment of a bool generate an error

Time:01-04

Ok, I have this code - (console app), but it fails for winforms, asp.net, or whatever.

        DataTable rstData = new DataTable();
        rstData.Columns.Add("VisitDate", typeof(DateTime));
        DataRow OneRow = rstData.NewRow();
        OneRow["VisitDate"] = DBNull.Value;
        rstData.Rows.Add(OneRow);

        DateTime? dtTest = (DateTime?)rstData.Rows[0]["VisitDate"] as DateTime?;

        bool testbvalue = true;

        Console.WriteLine(testbvalue.ToString());
        Console.WriteLine("Hit enter to continue");

        Console.ReadLine(); 

when I run the above, I get this error:

enter image description here

No errors in the previous code is triggered, and yet the simple bool assignment fails.

If I comment out the first part of code, say like this:

        //DataTable rstData = new DataTable();
        //rstData.Columns.Add("VisitDate", typeof(DateTime));
        //DataRow OneRow = rstData.NewRow();
        //OneRow["VisitDate"] = DBNull.Value;
        //rstData.Rows.Add(OneRow);

        //DateTime? dtTest = (DateTime?)rstData.Rows[0]["VisitDate"] as DateTime?;

        bool testbvalue = true;

        Console.WriteLine(testbvalue.ToString());
        Console.WriteLine("Hit enter to continue");

        Console.ReadLine(); 

Then of course the code works.

Edit: Stack trace shows this:

StackTrace  
"   at CSharpConsole.Program.Main(String[] args) in
C:\\Users\\Kalla\\source\\repos\\CSharpConsole\\Program.cs:line 20" string

so, stack trace does show the correct line - the debugger and VS highlights the wrong line.

CodePudding user response:

The bool assignment is fine.

The line above is producing the error i.e.

DateTime? dtTest = (DateTime?)rstData.Rows[0]["VisitDate"] as DateTime?;

For some reason, the debugger is pausing on the wrong line after the exception is thrown.

If you comment out the line with the bool assignment (and the related console output), you will see that the exception is reported on the Console.WriteLine("Hit enter to continue") line.

The direct cast (cast using brackets) on the DateTime assignment line is unnecessary and in fact the code runs fine if it is removed:

DateTime? dtTest = rstData.Rows[0]["VisitDate"] as DateTime?;

However, I'm still not sure why the debugger is pausing on the wrong line.

  • Related