Type Inference


With the query expression, the var keyword was used to specify the return type:

 var queryBrazilRacers = from r in Formula1.GetRacers()                    where r.Country == "Brazil"                    orderby r.Wins descending                    select r;

Until now the var keyword was not discussed. Happily, the var keyword is not the resurrection of VARIANT from the old COM as you might have feared. Behind the var keyword is the real type.

Assigning a number to the variable x that is defined with the var keyword, x is an int. The variable y is of type string.

 var x = 3; var y = "test";

After defining a value to the variable, the type is defined. You cannot change the type of a variable during runtime, as was possible with the VARIANT. The compiler replaces the var keyword by the real type. Visual Studio knows the real type as well and supports IntelliSense with variables defined with the var keyword.

What’s the advantage of having the var keyword? One advantage is that you don’t have to think about what is the return type of a method. This can get quite complex in special with generics. With the current query the returned type can also be declared as IEnumerable<Racer>:

 IEnumerable<Racer> queryBrazilRacers = from r in Formula1.GetRacers()                             where r.Country == "Brazil"                             orderby r.Wins descending                             select r;

This is not that complex, but there can be much more complex return types. While the use of the var reduces complexity in that case, with anonymous types the var keyword is really required. Anonymous types are discussed next.

Tip 

The var keyword has an important restriction: you can use locally within methods. You cannot use it with fields of a class or parameters of a method.




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net