Introduction:
In this article,i am going to explain about how to check the type at runtime using dynamic keyword in c# 4.0.
Main:
In sometimes we need to delay type resolution until runtime.This functionality is most useful in dynamic languages that require runtime binding,
for ex,
class Program
{
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
class Company
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsBig { get; set; }
}
static void Main(string[] args)
{
//declare three types that have nothing to do with each other,
//but all have an Id and Name property
Person p = new Person()
{ Id = 1, Name = “Ben”, Address = “Redmond, WA” };
Company c = new Company()
{ Id = 1313, Name = “Microsoft”, IsBig = true };
var v = new { Id = 13, Name = “Widget”, Silly = true };
PrintInfo(p);
PrintInfo(c);
PrintInfo(v);
try
{
PrintInfo(13);
}
catch (Exception ex)
{
Console.WriteLine(“Oops...can’t call PrintInfo(13)”);
Console.WriteLine(ex);
}
}
static void PrintInfo(dynamic data) //this DYNAMIC* keyword did this magic,
{
//will print anything that has an Id and Name property
Console.WriteLine(“ID: {0}, Name: {1}”, data.Id, data.Name);
}
}
class Program { class Person { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } } class Company { public int Id { get; set; } public string Name { get; set; } public bool IsBig { get; set; } } static void Main(string[] args) { //declare three types that have nothing to do with each other, //but all have an Id and Name property Person p = new Person() { Id = 1, Name = “Ben”, Address = “Redmond, WA” }; Company c = new Company() { Id = 1313, Name = “Microsoft”, IsBig = true }; var v = new { Id = 13, Name = “Widget”, Silly = true }; PrintInfo(p); PrintInfo(c); PrintInfo(v); try { PrintInfo(13); } catch (Exception ex) { Console.WriteLine(“Oops...can’t call PrintInfo(13)”); Console.WriteLine(ex); } } static void PrintInfo(dynamic data) //this DYNAMIC* keyword did this magic, { //will print anything that has an Id and Name property Console.WriteLine(“ID: {0}, Name: {1}”, data.Id, data.Name); } } |
Conclusion:
Hope this helps,
Happy Coding.
Great blog posting, very good information. waiting for your next post..