-1

I have an object animal:

class Animal{

}

I want to create an object of Animal, is there a difference between the lines on the class main?

class main{
     var myVar = new Animal();        // case 1
     Animal myAnimal = new Animal();  // case 2
}
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
newdev
  • 31
  • 3

1 Answers1

0

There is no difference. MSDN var description says:

An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

In other words, it is just a helpful way of writing the same code, with a little help of compiler. It is quite usefull when you are creating long types like:

var dict = new Dictionary<string, List<int>>();

instead of:

Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();

but was added at the same time as LINQ and anonymous types to make LINQ queries:

var outpus = someList.Where(x => x.SomeData == 0)
                     .Select(new 
                     {
                         FieldA = x.SomeField
                     });

so here compiler determines the anonymous type, you do not have to specify it.

You can read more about it on MSDN.

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58