-1
        var Id = from value in Enumerable.Range(0, 100)
                              select value;

        IEnumerable<int> ids = from value in Enumerable.Range(0, 100)
                              select value;



        foreach (var v in Id)
        {
            Console.WriteLine(v.ToString());
        }

        foreach (var x in ids)
        {
            Console.WriteLine(x.ToString());
        }

Both will do the same job, but what is the difference?

Robert Harvey
  • 200,592

1 Answers1

6

There is no difference between the two, except for readability. The second example (ids) is more explicit than the first and perhaps more readable. But, readability is a matter of taste/opinion with many different viewpoints. Here are some guidelines...

 public void SampleCode()
        {
            //Use of var is encouraged when  declaration needlessly clutters code
            Widget widget1a = new Widget();  //No
            var widget1b = new Widget();  //Yes, I know I am getting a widget.

            //Use of var is encouraged when method name defines return type 
            //or return is type is known without further need of code inspection
            Widget widget2a = GetWidget(); //OK (Verbose)
            var widget2b = GetWidget(); //Yes, But...
            //Danger, Will Robinson!  if GetWidget returns a foo...Code review time!

            //Use of var is discouraged when method offers new clue to type 
            //without further code inspection
            Widget widget3a = Process(); //Yes, intent is clear without any further inspection.
            var widget3b = Process(); //No, What does Process do?
        }
Jon Raynor
  • 11,773