C# Assert Method

.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOfLambda Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple Window

Assert  sends a strong message to the developer. An assertion interrupts normal operation of the program but does not terminate the application. The Debug.Assert method in the System.Diagnostics class provides a way to implement this.

Example.  We explore the Debug.Assert method in the C# language. We use Assert to catch a condition that should not occur and would be a bug if it did. This is not an exception. It will never occur in finished code.

Note:Debug calls are compiled out when in Release mode. Exceptions are always kept in the code.

Exception
C# program that uses Assert method

using System;
using System.Diagnostics;

static class Program
{
    static void Main()
    {
	int value = -1;
	// A.
	// If value is ever -1, then a dialog will be shown.
	Debug.Assert(value != -1, "Value must never be -1.");

	// B.
	// If you want to only write a line, use WriteLineIf.
	Debug.WriteLineIf(value == -1, "Value is -1.");
    }
}

Result
    A. The dialog is displayed.
    B. Message is written to the Output: Value is -1.
The second parameters  to Debug.Assert and Debug.WriteLineIf are expressions. They will be evaluated by the runtime before being converted to a Boolean value (true or false) and then passed as a value to the methods themselves.

Then:The Debug.Assert method will be executed. It internally checks the value of this expression evaluation.


Discussion.  There are more static methods on the Debug class in the System.Diagnostics namespace in the C# language. You can access these methods by typing "Debug" and pressing period in Visual Studio, which will display Intellisense. Debug.Write Debug.WriteLineIf, WriteIf

Overview:The Assert method is most disruptive, and other methods such as Debug.WriteLine are less of a burden to encounter.


Summary. Here we looked at an example of using the Debug.Assert method and an expression-based parameter to display an error condition to a developer of the program. We saw the error message displayed by Assert by a real C# program.


转载地址:http://www.dotnetperls.com/assert

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值