简体   繁体   中英

Why does this simple assignment of a bool generate an error

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:

在此处输入图像描述

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.

The bool assignment is fine.

The line above is producing the error ie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM