+ 3

Difference between var and int

Is there a difference between "var num = 15" and "int num = 15"? Performance wise or memory wise? Thanks in advance.

30th Aug 2016, 6:09 AM
Miguel Roa
Miguel Roa - avatar
9 Answers
+ 9
All of the other answers are wrong. C# is strongly typed, which means that every variable needs to be defined with a type. it can not change type at run time. the keyword var can only be used if the variable type can be inferred by the compiler. it's only function is to make the code look more clean. I.e. let's say I want to make a list of strings. I could either do this: List<string> myList = new List<string>(); From the right hand side if the expression the compiler knows the type, so it is redundant to write it twice and you can instead use the var keyword var myList = new List<string>(); what you cannot do is something like this: var myList; myList = new List<string>(); because the compiler does not know which type to give myList when it is declared
30th Aug 2016, 4:52 PM
René BjÞrn Hansen
René BjÞrn Hansen - avatar
+ 5
If you know then there is no need of using var keyword just use the specific type that you want :) Don't forget to thumbs up my answer :)
30th Aug 2016, 12:22 PM
Ammar Ahmad
Ammar Ahmad - avatar
+ 4
As you know every variable has a specific type and you declare variable according to your need as which type of variable you want.. Right? But in some cases you don't know what type or variable you need actually.. In this case you can declare a variable with var keyword. The compiler will assign a suitable variable type to you variable during the execution of program :) hope you understand.. If any problem comment again :)
30th Aug 2016, 12:09 PM
Ammar Ahmad
Ammar Ahmad - avatar
+ 2
I understand the part in which "I don't know the type". But what if I do? If I know that I will be using a number, is there any difference?
30th Aug 2016, 12:12 PM
Miguel Roa
Miguel Roa - avatar
+ 2
if U have numbers U want to stor it ..so .U mast use " int "..
4th Sep 2016, 6:17 PM
Fatma Hussein Al-Amoudi
Fatma Hussein Al-Amoudi - avatar
+ 1
Using var means that on the time of the initialization you do not know what variable type you need so you let the c# compiler decide.
30th Aug 2016, 1:08 PM
Ivelin Dinev
Ivelin Dinev - avatar
0
Using var means that on the time of the initialization you do not know what variable type you need so you let the c# compiler decide.
30th Aug 2016, 1:08 PM
Ivelin Dinev
Ivelin Dinev - avatar
0
Var can be Int, double, char und string. But int is just whole number, Var x='H'; //this is char Var x=15; //this is int BUT ! int x=15 //whole number int x='H' //ERROR
1st Mar 2017, 10:55 PM
Andrea Calero
Andrea Calero - avatar
- 4
a
30th Aug 2016, 9:08 AM
dinesh