C# - What does the Assert() method do? Is it still useful?

后端 未结 9 1698
青春惊慌失措
青春惊慌失措 2020-12-12 10:37

I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should

9条回答
  •  一生所求
    2020-12-12 10:56

    First of all Assert() method is available for Trace and Debug classes.
    Debug.Assert() is executing only in Debug mode.
    Trace.Assert() is executing in Debug and Release mode.

    Here is an example:

            int i = 1 + 3;
            // Debug.Assert method in Debug mode fails, since i == 4
            Debug.Assert(i == 3);
            Debug.WriteLine(i == 3, "i is equal to 3");
    
            // Trace.Assert method in Release mode is not failing.
            Trace.Assert(i == 4);
            Trace.WriteLine(i == 4, "i is equla to 4");
    
            Console.WriteLine("Press a key to continue...");
            Console.ReadLine();
    

    Run this code in Debug mode and then in Release mode.

    You will notice that during Debug mode your code Debug.Assert statement fails, you get a message box showing the current stack trace of the application. This is not happening in Release mode since Trace.Assert() condition is true (i == 4).

    WriteLine() method simply gives you an option of logging the information to Visual Studio output.

提交回复
热议问题