+ 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;

23rd Jun 2016, 8:38 AM
Programmer
Programmer - avatar
6 Respostas
+ 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
23rd Jun 2016, 12:20 PM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 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
30th Jun 2016, 3:39 PM
Ibra Code
Ibra Code - avatar
+ 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
25th Jun 2016, 10:04 AM
Mehaboobmunna Annigeri
Mehaboobmunna Annigeri - avatar
+ 1
Thanks Prakash
27th Jun 2016, 5:22 AM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
0
Var num=value; This is the syntax dear. you must initialize the variable. @Venkatesh explained very well
24th Jun 2016, 5:58 PM
Prakash VL
Prakash VL - avatar
- 1
Simply because any number declared should be an integer and not a var
4th Jul 2016, 2:12 PM
Lewis miles
Lewis miles - avatar