Monday 19 June 2017

Dynamic Keyword

The dynamic keyword lets you instantiate objects at run-time, that is it'll skip compile time error checking and trust that you know what you're doing.
Make sure to include a reference to Microsoft.CSharp.dll and that you're using the 4.0+ run-time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynamicExample
{
    public class Person
    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public DateTime BirthDate { getset; }

        public int GetAge()
        {
            var Today = DateTime.Now;
            var age = Today.Year - BirthDate.Year;
            return BirthDate > Today.AddYears(-age) ? --age : age;
        }

        public override string ToString()
        {
            return string.Format("{0} {1}", FirstName, LastName);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            dynamic dynamicPerson = new Person() {
                FirstName = "Pawel",
                LastName = "Chooch",
                BirthDate = new DateTime(1984, 1, 31) };

            //Works Great
            Console.WriteLine(dynamicPerson.GetAge());

            //Crashes program at runtime, no error at compile time
            Console.WriteLine(dynamicPerson.GetAge(23));
        }
    }
}