20 Feb 2012

Implicitly Typed Local Variables

(bien local loai ko tuong minh – ngam dinh)
Should you use the var keyword to declare a local variable in C#?
whether and when it is a good idea to use implicit typing!!! This section focuses on the usefulness of declaring local variables using the var keyword.
Table 7-2. The var Keyword: Dispelling the Fallacies
Fallacy
Fact
There is an erroneous belief that when a local variable is declared using the var keyword that then the variable is a variant type,
Another misconception is that the var keyword makes C# a weakly typed programming language.
Yet another fallacy is that variables declared with the var keyword are dynamically typed at runtime.
There are situations where the var keyword is required.
   1: var album = new { Artist = "U2", Title = "Rattle And Hum" };
   2: Console.WriteLine("\"{0}\", by {1}", album.Title, album.Artist);


  • Using the var keyword the code is made more readable


   1: private void Process1()
   2: {
   3:     List<Artist> artists = new List<Artist>();
   4:     Dictionary<Artist, Album> albums = new Dictionary<Artist, Album>();
   5:     ...
   6: private void Process2()
   7: {
   8:     var artists = new List<Artist>();
   9:     var albums = new Dictionary<Artist, Album>();
  10:     ...

Listing 7-6. Sample Code That Uses Explicit Typing


   1: ApplicationRepository repository
   2:     = new ApplicationRepository();
   3: string lastNameCriteria = "P";
   4: Controller controller = new Controller(repository);
   5: ApplicationCollection results = controller.Search(lastNameCriteria);
   6: foreach (var result in results)
   7: {
   8:     Console.WriteLine("{0}, {1}",
   9:     result.LastName,
  10:     result.FirstName);
  11: }

Listing 7-7. Sample Code That Uses Implicit Typing


   1: var repository = new ApplicationRepository();
   2: var lastNameCriteria = "P";
   3: var controller = new Controller(repository);
   4: var results = controller.Search(lastNameCriteria);
   5: foreach (var result in results)
   6: {
   7:     Console.WriteLine("{0}, {1}",
   8:     result.LastName,
   9:     result.FirstName);
  10: }

At some future date, the signature of the Search method could change to return the
IEnumerable<Application> type, as follows:


   1: public IEnumerable<Application> Search(string lastNameCriteria)


This change has no impact on the code in Listing 7-7 because the compiler has implicitly typed the results variable. However, this change causes the code in Listing 7-6 to generate a compiler error something like the following:

Error Cannot implicitly convert type 'IEnumerable< Application>' to 'ApplicationCollection'.

 Practice 7-2 Use the var Keyword to Loosely Couple Local Variables from Their Implicit Type

No comments: