Thursday 12 February 2009

Session Oveview 2 (Local Type Inference)

Session Oveview 2 (Local Type Inference)

 Local Type Inference (aka Implicitly Typed Local Variable)
 Var keyword (make development easier)
 Emphasis on local, as in local scope.

NOTE: Var keyword works only with local scope.

e.g.
var first = 1; // first will be of type System.Int32
Console.WriteLine (“Type of first {0}”, first.GetType()):
var name = “rajesh”; // name will be of type System.String
Console.WriteLine (“Type of name {0}”, first.GetType()):

Points to note:
1. var canno be part of a return value of a function.
2. var order; This is invalid as this has to be initialized.
3. var forth = null; This is invalid as null is basically unknown.
Some examples:
String[] countries = new string[]
{“India”, “China”, “Israel”, “Russia”};
// get all countries which starts with “I”
var iCountry = from c in countries
where c.StartsWith(“I”)
select s;
foreach(var country in iCountry)
Console.WriteLine(country);

The output of the above snippet will be
India
Israel

No comments: