Programming languages can be divided in to two categories strongly typed and dynamically typed. Strongly typed languages are those where the checks happen during compile time while dynamic languages are those where type checks are bypassed during compile time. In dynamic language object types are known only during runtime and type checks are activated only at run time.
Now try the below code out. In the below code I have created a dynamic variable which is initialized with a string data. And in the second line I am trying to have fun by trying to execute a numeric incremental operation. So what will happen now ?.... think.
dynamic x = "c#";
Now this code will compile fine without any complains. But during runtime it will throw an exception complaining that the mathematical operations cannot be executed on the variable as it’s a string type. In other words during runtime the dynamic object gets transformed from general data type to specific data type (ex: - string for the below code).
Practical uses of Dynamic keyword: -
One of the biggest practical uses of dynamic keyword is when we operate on MS office components via interop.
So for example if we are accessing Microsoft excel components without dynamic keyword, you can see how complicated the below code is. Lots of casting happens in the below code, right.
// Before the introduction of dynamic.
Application excelApplication = new Application();
((Excel.Range)excelApp.Cells[1, 1]).Value2 = "Name";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];
Now look at how simple the code becomes by using the dynamic keyword. No casting needed and during runtime type checking also happens.
// After the introduction of dynamic, the access to the Value property and
// the conversion to Excel.Range are handled by the run-time COM binder.
dynamic excelApp = new Application();
excelApp.Cells[1, 1].Value = "Name";
Excel.Range range2010 = excelApp.Cells[1, 1];