The “dynamic” is the new keyword introduced in C# in version 4.0.This adds some kind dynamic capabilities in this statically typed language.But before getting into the details of how this new keyword will be used and what are it’s implication I would prefer to take a quick look into what are dynamic languages, duck typing etc.
i = "Sankarsan" j = "Bose" puts i + j # This will print as "SankarsanBose" i = 50 j = 50 puts i + j #This will print 100
So the type of the variables is defined dynamically at runtime based on the value it is holding.
Along with this another important thing to notice is how method dispatch is handled in dynamic languages.Let’s take a look into the following piece of code in Ruby.
class WordProcessor def print puts "Printing Document" end end class Spreadsheet def print puts "Printing Spreadsheet" end end class OfficeSuite def print(p) p.print() end end w = WordProcessor.new(); s = Spreadsheet.new(); o = OfficeSuite.new(); o.print(s); o.print(w);
Here the output will be:
Here we are not bothered about what type “p” has, as long as it supports a method called print() we are good.This is what is known as “Duck Typing“.The essence of this is
This means as long as the object has ability to execute a method it is fine I need not bother about the type (that is it is a duck or not)
Actually with the new “dynamic” keyword in C# we are going to have the ability of duck typing.
But before getting I would like explain briefly about DLR (Dynamic Language Runtime) in my next post.This will make it easy to understand later how “dynamic” is implemented.
PS: Some of the contents here are taken from earlier post in arch2dev.com