Hello, My name is Nima Owji. I am 14. I am a C# programmer. Today, I wanna tell you what are the differences between var and dynamic in C#.
First of all, I'm gonna tell you when did they add to C#.
"var" added in C# 3 but "dynamic" added in C# 4. They aren't available in earlier versions, so you should use C# 4 to up.
You know how to declare a variable in C#.
public int x = 5; private string y = "nima"; bool z = true;
As you know, You should use a data type for your variable, then assign a name. You can also assign a value to your variable in declaration time, like the example.
This is the format of variables:
[Scope] [DataType] [Name];
As you know we use "int" or "long" ... for numbers, "string" for strings and text. We all tell the compiler what is the datatype in the normal declaration.
var will use like a data type in C#. You can assign all values to it, for example, "int", "string", "long", "List".
But how do we use them?
Look at the example:
var x = 5; var y = "nima"; var z = true;
It will select the best data type for your variable automatically.
But you can't change their data types like variables too. For example, this code will not work!
var x = 5; x = "nima";
Because you are assigning a string to an int variable.
Now, what are the "dynamic"s?
dynamics are another type like "var". It will select the best data type for your variable based on your value. dynamics won't be checked at compile time. They be will checked at runtime.
dynamic x = 5; dynamic y = "nima"; dynamic z = true;
But what is the difference between "dynamic" and "var"?
As I told you, you can't change the data type of a variable. But you can do that in "dynamic"!
Look at this example:
dynamic x = 5; x = "nima"; x = 'a'; x = false;
This will work correctly.
These were the most important things you have to know about "var" and "dynamic" in C#.
I hope you liked this article.
Please like this article and follow me on Twitter: @nima_owji
Thank you so much. Byeeee!