Home > Back-end >  Implicit type and explicit type
Implicit type and explicit type

Time:07-14

I have read on geeks for geeks about the var keyword => the article link.
It said: "var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value."
I just couldn't find information about the explicit type, the one I always use. So I wonder what is the initial value and what are the differences between the Implicit type and the Explicit type?
*Examples:

var i = 10; // Implicitly typed.
int i = 10; // Explicitly typed.

CodePudding user response:

You do not need to set an initial value for an explicit type.

int i;
i = 10;

For an implicit type you must.

var i;  // Error
i = 10;

Because the compiler translates this to a normal concrete type.

var i = 10; // is compiled to "int num = 10;"

"var" only shortens and simplifies the code writing for the programmer.

You can see it on SharpLab.

CodePudding user response:

Initial value means the value when defining the variable.

For example, var i becomes int because it is assigned to to value 10 which is the initial value (of type int).

More about the difference between the two in this Official documentation

CodePudding user response:

what is the initial value

-The initial value is the one that you assign when creating a variable.

int i=1 //<---Initial value

var i=1 //<---Initial value

what are the differences between the Implicit type and the Explicit type

-The implicit type, as you've seen in GeeksForGeeks, is the variable that specifies the type of a variable based on initial value.

For example, if you create an implicit variable with the initial value of 120.23f, the compiler will take this variable as a Single type, or if you initialize an implicit variable with the initial value of "G", the compiler will take it as a Char type. Just check out the list of variables and what kind of inputs do they take, and you'll understand how implicit variables works. They have useful uses such as:

Two particularly important reasons for using "var" are when using anonymous types and language-integrated query (LINQ). In these cases, the type of variable required may not be known or may not even exist.

Some useful links: C# Variable list , Uses of Var

  • Related