Thursday 15 June 2017

Directives: #define, #undef, #if, #elIf, #else, #error, #warning

When a symbol is defined using #define it's as if you are setting a flag to true, if you #undef it then you are setting a flag to false. You can only #define and #undef at the very top of your file before anything else.

Then you can use the #if, #elif, #else properties to check if your flag is set. you can use boolean operators like && and || to check if multiple flags are set.

#define flag1
#define flag2
#undef flag1

using System;
using System.Collections.Generic;

namespace DEBUG00
    class Person
        public string Name { get; set; }
        public DateTime Birthdate { get; set; }

        public Person(string Name)
            this.Name = Name;

        public Person(string FirstName, DateTime Birthdate)
            : this(FirstName)
            this.Birthdate = Birthdate;

        public int GetAge()
            var today = DateTime.Today;
            int age = today.Year - Birthdate.Year;
            return Birthdate > today.AddYears(-age) ? --age : age;

        public override string ToString()
#if flag1
            return string.Format("{0} {1}",FirstName);
#elif flag2
            return string.Format("{0} {1} is {2} years old", Name, GetAge());
            return base.ToString();
    class Program
        static void Main(string[] args)
            List<Person> ppl = new List<Person>();

            ppl.Add(new Person("Pawel", new DateTime(1984, 01, 31)));
            ppl.Add(new Person("Tomek", new DateTime(1988, 08, 28)));
            ppl.Add(new Person("Magda", new DateTime(1984, 06, 28)));

            foreach (var p in ppl)


in the above example we call a different toString() on our person class based on which flag is set

#Error #warning

the #error and #warning directives will create the corresponding warnings and errors to appear in visual studios error list. so the following

#warning this is my custom warning
#error this is my custom error

would produce

acting just like normal warnings and errors where errors interrupt the build process.

the #DEBUG directive will let you isolate logic that you one want to run when you're application is set to debug. this can be useful if you want some specific logic to only fire when developing and not in production.