Jul 29 2007

Implicitly Typed Local Variables

Category: C# 3.0Bil@l @ 14:56

Implicitly Typed Local Variables is a general prupose way of declaring variables without the need to specify the data type. The data type will be infered implicitly from the initializer data. It is strongly typed variable
that cannot take as input a data type other than the one used on initialization time. This proves that "var" is not the same as "Dim" in VB/.NET. Dim can take different data types, however, "var" only takes values of the same data type that was used upon initialization.


 Things you cannot do with Implicitly Typed Local Variables
  You cannot declare an ITLV without specifying an initializer.
  You cannot set the value of a VAR to NULL.
  You cannot change the data type of an already defined VAR variable.
  
 Things you cannot do with Implicitly Typed Local Variables
  You can assign one VAR to another.
 
 An example of using a "var" is as follows:

 // Simple string
 var intValue= 5;

 // Array of integers
 var arrInt= new[] {1, 2, 3, 4};

 // Array of objects
 var arrObject= new[] {new Point(), new Point()};


 "var" is mainly used to shape the results of a Query Expression because sometimes you might return a result that cannot be used explicitly as follows:

 var results=  from c in db.customers
   select new MyCustomer {
    ID= c.ID,
    Name= c.Name
   };

 Now, we can navigate through the results as follows
 foreach (MyCustomer cust in results) {
  Console.WriteLine("{0}, {1}", cust.ID, cust.Name);
 }
 
 
Hope this helps you,
Regards

Tags:

Comments are closed