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#.
When did they add to 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.
How to use variables?
You know how to declare a variable in C#.
For example:
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.
How to use "var"
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?
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.
Like this:
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"!
Example for "dynamic"
Look at this example:
dynamic x = 5;
x = "nima";
x = 'a';
x = false;
This will work correctly.
The end
These were the most important things you have to know about "var" and "dynamic" in C#.
I hope you liked this article.
Don't forget to like it
Please like this article and follow me on Twitter: @nima_owji
.
Thank you so much. Byeeee!
Top comments (10)
what is the meaning of unicorn which is beside of heart
It's a step up compared to the ♥️: something along the lines of "I not only like this, I think it's extra special".
Yes, I think too
I don't know too XD I think it works like like button. press it
Thanks!
You're welcome
Thank you so much. Thankssss
If you have any questions, ask me!
Please follow me on Twitter!
Please don't forget to like it!