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 { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
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));
}
}
}