.
One of the new language features added in c# 3.0 type
inference. its look like a variant data type in vb. But it is not as same as
variant in vb. What is type inference is?
Consider the following statements
int i=10;
is equal to
var i=10;
the compiler
determines what the type of variable is by the value of the variable is
initialized to.
In the second statement variable is not declared as int. but
it is taken as int because the integer value 10 is assigned to int.
The compiler will take it as int, as long as it in scope.
The variable is here still strongly typed. The var key is
valid inside a method.
we can not declare class –wide variables with var keywords.
the variables declared with var keyword can not have its initial Value as null
and also value cannot be a lambda expression, anonymous method or method group
(without a cast). For the variables which are declared with var keyword the
compile-time type of the value is used for the type of the variable and any
further uses of the variable are only checked against the type determined by
the initial declaration and assignment.
Sample program:
Using System;
Class VarSample
{
static void Main (String[]
args)
{
var item=”idli”;
var price=10;
var isFood=true;
Type itemType=item.GetType();
Type priceType=price.GetType();
Type isFoodType=isFood.GetType();
Console.WriteLine(“item is type of “+itemType.ToString());
Console.WriteLine(“price is type of “+priceType.ToString());
Console.WriteLine(“isFood is type of “+isFoodType.ToString());
}
}
Output:
Item is type of System.String
Price is type of System.Int32
isFood is type of System.Bool
No comments:
Post a Comment