Assert Method
why we use assert method.
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
saurabh mittal152 reputationPosted Apr 2, 2014, 3:06 AM EDT
We use assert method to check business rules.like if we take age As int .
In real world age should not be negative.but if we give -30.it will accept this because
it is not an exception.this is a bug. for check this type of rules or bug we use assert.
how can we use this for this u can see this Link
thanks
Abhay ShankerRank #375 · 6.7K reputationPosted Apr 2, 2014, 3:05 AM EDT
Example
We explore the Debug.Assert method in the C# language. Use Assert to catch a condition that shouldn't occur and would be a bug if it did. This is not an exception, as it will never occur in finished code. Debug calls are compiled out when in Release mode. Exceptions are always kept in the code.
Program that uses Assert method [C#]
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.