+ 2
why will: Var num; num=42; cause an error while: int myAge; myAge=18; will not? Is it that when working with Var we need to write it like this: Varnum =15; Varnum; number=15;
6 Respuestas
+ 5
In the case of int myAge; Compiler known that myAge is a integer variable.
Whereas var num; Compiler doesn't known what type of value it's gonna to be hold. That's why compiler is throwing an error. Because of this var type variable should be initialize.
Usage for var keyword is we don't want to specify the datatype explicitly, compiler will identify the type of the variable through intialize value.
Hope you understand this well
+ 3
the var keyword is used to declare implicitly typed local variables.
××>restrictions for an implicitly typed local variable
1. The variable must be declared and initialized with some value or expression
var age; //error, no initializer to infer the data type
var age = 5; // valid
2. They cannot be initialized to null type
var name = null; // Error, null type is not allowed
3. The var keyword cannot be used as a return type
var Calculate(int a, int b)// error
4. The var keyword cannot be used in the argument list of a method
int Calculate(var a, var b) // error
5. The local variable declaration cannot include multiple declarations
var a =10, b = 13, c =34; // error
+ 2
you have to initialize the var variable the moment you declare it. you cant declare it in one sentence and initialize it in other. the var has to know type of variable it is about to store. This is why you need to declare it in one sentence. Then the var will calculate the right hand side of equation and determine the type of output and assign appropriate variable type
+ 1
Thanks Prakash
0
Var num=value;
This is the syntax dear. you must initialize the variable. @Venkatesh explained very well
- 1
Simply because any number declared should be an integer and not a var