dynamic vs object

      People keep asking me what is the difference between “dynamic” and the old friend “object”. Well, answer is a little tricky; in order to show the difference, it’s better to take a look at both of them more detailed.

     Let me start with the old friend “object”, that is nothing but a shortcut for “System.Object”; it’s a part of our life since the first release of C#. Object is very powerful, cause you can assign almost any value. In order to compare them lets take a loot a example below:

object obj = 1;

 if (obj.GetType() == typeof(int)){
     Console.WriteLine("of course type is int");
 }  else {
     Console.WriteLine("Whole post is wrong :P");
}

Console.ReadKey();

One may expect "Whole post is wrong 😛", since obj is declared as object not the int; but output of the code is simply "of course type is int"; cause value stored at obj is of type int. Although value of obj is of type int and code runs without any problem, as soon as you perform any int related operation, like sum, code will not even compile:

object obj = 1;

 if (obj.GetType() == typeof(int)){
     Console.WriteLine("of course type is int");
} else {
     Console.WriteLine("Whole post is wrong :P");
}

obj = obj + 1;

(error CS0019: Operator ‘+=’ cannot be applied to operands of type ‘object’ and ‘int’)

In order to compile your code, you need to cast obj first:

object obj = 1;

 if (obj.GetType() == typeof(int)){
     Console.WriteLine("of course type is int");
} else {
     Console.WriteLine("Whole post is wrong :P");
}

obj = (int)obj + 1;

of course having a compiled code doesn’t means that everything is fine. Anyone can have a compiled code like below, which gives run-time error (InvalidCastException)

object obj = 1;

 if (obj.GetType() == typeof(int)){
     Console.WriteLine("of course type is int");
} else {
     Console.WriteLine("Whole post is wrong :P");
}

obj = (string)obj + 1;

Compiler does not let you perform any mathematical operation on obj, as long as explicitly indicated. But still can be explicitly cast to any other type, which causes run-time exceptions.

Here comes “dynamic” in. Dynamic  comes with C# 4.0 and instructs compiler not to perform additional rules on your type. You can use it just like you do with the “object”:

dynamic obj = 1;

 if (obj.GetType() == typeof(int)){
     Console.WriteLine("of course type is int");
 }  else {
     Console.WriteLine("Whole post is wrong :P");
}

Console.ReadKey();

Also, following code will compile without any compiler error:

dynamic obj = 1;

 if (obj.GetType() == typeof(int)){
     Console.WriteLine("of course type is int");
} else {
     Console.WriteLine("Whole post is wrong :P");
}

obj = obj + 1;

You don’t need to cast obj to int as you do with object. This is the main difference between object and dynamic. By using dynamic keyword, you instruct compiler not to perform additional rules on your type. It will instruct compiler that its type can be known only at run-time, so compiler doesn’t try to interfere.

By using dynamic, your code’s readability will improve, you don’t have to perform additional explicit cast.

“WITH GREAT POWER THERE MUST ALSO COME – – GREAT RESPONSIBILITY!”

Dynamic is very handy; but must use very carefully. It is still as dangerous as object is and you should apply all check-points within your code.

Fatih Boy

Ankara'da yaşayan Fatih, bir kamu kurumunda danışman olarak çalışmaktadır. ALM süreçleri, kurumsal veri yolu sistemleri, kurumsal altyapı ve yazılım geliştirme konularında destek vermektedir. Boş zamanlarında açık kaynak kodlu projeler geliştirmeyi ve bilgisini yazdığı makalelerle paylaşmayı seven Fatih, aynı zamanda Visual C# ve Visual Studio teknolojileri konusundan Microsoft tarafından altı yıl üst üste MVP (En Değerli Profesyonel) ödülüne layık görülmüştür. İş hayatı boyunca masaüstü uygulamaları, web teknolojileri, akıllı istemciler gibi konularda Asp.Net, Php, C#, Java programlama dilleri ve MySql, MsSql ve Oracle gibi veritabanı yönetim yazılımları ile çalışmıştır. İngilizce ve Türkçe olarak yayınlanan makalelerini gerek İngilizce bloğunda, gerekse de Türkçe bloğunda bulabileceğiniz gibi web sitesinden de açık kaynak kodlu geliştirdiği yazılımlarına ulaşabilirsiniz. vCard - Twitter - Facebook - Google+

2 yorum

  1. Koray Bostancı   •  

    Happy to see a post from you after a long time no post period Fatih. I hope you keep blogging.. 🙂

  2. Cenap   •  

    Ms. finally getting close to what PHP or action script did a long time ago!!! (Too cruel?)

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir