Wednesday, 14 June 2017

Asserts

Asserts are in the system.diagnostics namespace, they allow you to view the stack trace if a condition is not met, that is the condition is false. they like the debugger display are an excellent tool for debugging code and trying to find those tough bugs.

using System;
using System.Diagnostics;

namespace pc.AssertsExample
{
    class Program
    {
        public class Person
        {
            public string Name { getset; }
            public DateTime BirthDate { getset; }
            public Person(string Name, DateTime BirthDate)
            {
                this.Name = Name;
                this.BirthDate = BirthDate;
            }
            public int GetAge()
            {
                DateTime today = DateTime.Today;
                int age = today.Year - BirthDate.Year;
                return BirthDate > today.AddYears(-age) ? --age : age;
            }

            public override string ToString()
            {
                return Name + " is " + GetAge();
            }
        }
        static void Main(string[] args)
        {
            var pawel = new Person("Pawel"new DateTime(1984, 1, 31));
            Debug.Assert(pawel.GetAge() == 30, "Pawel isn't 30");
        }
    }
}

Running the above will result in the following message box


We have three options:
  1. Abort: the program ends 
  2. Retry: you step into the code at the assert statement. 
  3. Ignore: continues on
we also see our friendly message "Pawel isn't 30", should we have numerous asserts in our application we can use this parameter to differentiate them we also see the stack trace. Asserts will only fire if your program is set to debug mode, if it's in release nothing will happen. they are a nice alternative to message boxes and they're more in your face then just your regular Debug.WriteLine.