dynamic intExample = 1;It will print out put on web page as following.
Response.Write(intExample);
dynamic floatExample = 2.5;
Response.Write(floatExample);
dynamic stringExample = "DotNetJaps";
Response.Write(stringExample);
Now, you will have question what's new in that. It could be also done with var keyword . Yes, you can do same thing with var but dynamic keyword is slightly different then var keyword.
Diffrence between var and dynamic keyword:
var keyword will know the value assigned to it at compile time while dynamic keyword will resolve value assigned to it at run time. I know you guys don't believe me without example. So let's take example of string.
string s = "DotNetJaps-A Blog for asp.net,C#.net,VB.NET";
var varstring=s;
Response.Write(varstring.MethodDoesnotExist());
string s = "DotNetJaps-A Blog for asp.net,C#.net,VB.NET";This will compile. So it is the difference between dynamic and var keyword. With dynamic keyword anything assigned to it like property,objects operators anything that will be determined at compile time. It can be useful while we are doing programming with com,JavaScript which can have runtime properties.
dynamic varstring=s;
Response.Write(varstring.MethodDoesnotExist());
Happy Programming...
Thank you for this article!
ReplyDeleteMay you add the third "dynamic" possibility by using object data type too?
e.g.:
string s = "DotNetJaps-A Blog for asp.net,C#.net,VB.NET";
object objstring = s;
Console.WriteLine(objstring.MethodDoesnotExist());
Its helpme lot,
ReplyDelete1 more diffe
var can use in the functions only
means declarion in the class does not allow
internal class Test
{
var a=0;//error
private void Function()
{
var x=0;// no error
}
}
but "dynamic" can call from anywhere like "int"
Is code written in first block is correct using c#.net?
ReplyDeleteNice one...Check this blog for more info about var and dynamic:-
ReplyDeletesenthilvijayalakshmi.blogspot.in/2013/03/difference-between-var-and-dynamic.html
thanks for sharing!!
ReplyDelete