Partilhar via


The Var Of The Worlds

Hello folks,

This time we will explore LINQ over a series of Posts.

As you must be knowing the age old "var" is back. But, is it the same old var that used to be in VB 6.0 days?

Precisely its not the same it has got a number of new features:
- You have to declare and instantiate it at the same line of code. Reason: It is smart enough to understand the assigned data type, and it becomes it.
 
var s = int.MaxValue; // it becomes Int32
var s2 = double.MaxValue; // it becomes double
var s3 = "The Var Of The Worlds" // string

- You cannot assign multiple data types to it. Any attempt to do so results in a compile time error.

Code with var:

    1: class Program
    2: {
    3:     static void Main(string[] args)
    4:     {
    5:         var s = from m in typeof(string).GetMethods()
    6:                 select m.Name;
    7:         foreach(string str in s)
    8:         {
    9:             Console.WriteLine(str);
   10:         }
   11:         Console.Read();
   12:     }
   13: }

Code without a var:

    1: class Program
    2: {
    3:     static void Main(string[] args)
    4:     {
    5:         IEnumerable<string> s  = 
    6:             from m in typeof(string).GetMethods()
    7:             select m.Name;
    8:  
    9:         foreach(string str in s)
   10:         {
   11:             Console.WriteLine(str);
   12:         }
   13:         Console.Read();
   14:     }
   15: }

Comments