This article is to demonstrate use of dynamic keyword in c# .
New features of .NET 4.0
There are very popular new features came in .NET 4.0 .some of them
Let's look into Dynamic type now
First of all check your .NET framework version in your development environment
otherwise it will not work. If you are using visual studio 2010 then it’s fine,
no need to worry. And those who are
using VS2008 or lower version please have a look on your .NET Version.
Let’s talk about Dynamic type in C#.
The bullet line about dynamic variable is “Everything will be in run time”.
What does it mean ? It means that if you declare any object or variable as a
dynamic type compiler will not bother about any operation associated with this
object or variable. Getting confused?
Please continue reading till this paragraph, I
can assure you will understand. Take one example to understand it. Suppose you have one variable declared dynamic
type. And with this variable you want to do some restricted operation (some
restricted operation, and you know compiler will not allow you), Then in compile
time compiler will never complain you to do this operation but in run time it
will show error. This behavior proves this statement “Everything will be in run time”.
Now let’s look practically.
static void Main(string
DateTimeVariable = "Sourav";
d = "Sourav"; //Show error Message
Here you can see when I was trying to assign a string to a
DateTime variable then compiler is immediately complaining me but in case of dynamic DateTimeVariable = "Sourav";. It’s not showing any error at compile time, though it will throw at run time.
See another more example of dynamic object
objD = new TestDynamic();
objD.CallDynamic(100, 100); //No error ,though
function prototype mismatch
Here you can see I have created object
of TestDynamic class called objD and using this object I am trying to call CallDynamic()
function with two parameter as function argument like
in compile time my compiler is not complaining me at all. Because I have
declared objD as a dynamic object . And we know all operation associated with
dynamic object perform in run time.
clear few concept of dynamic variable.
If you make some operation with loosely
type variable(like var keyword) then the result will also be dynamic type. For example
value = 100;
newVal = value + 100;
If I try to get property or function
of newVal variable (After operation with dynamic variable) I am not getting
anything. But in general if I declare any var variable I can access any
property in compile time itself because it convert into strong type in compile
assign anything in dynamic variable . Then difference between var and dynamic ?
Yes, you can assign any value in dynamic variable. Like this
static void Main(string
a = 100;
b = "sourav";
Now, You may think in var also we can store any data. Then what is
the difference between them ? Difference
var the type conversion operation performs in compile time and in case of
dynamic it’s in run time.