Language of Integrated Query - Part Two

So I am back again to explain some of the flexibilities offered by LINQ. The series is not really related to part one other than the LINQ part, but if you are still curious here is the link:
So today I am going to talk about fluent APIS. Now the terminology actually came from Ruby on Rails where it's easy to read the code and you dont have to add /read comments. If you check the code here, in the method ‘Speak,’ we created two variables and passed them to a ‘talk’ function. There is no way of telling here what the code is doing unless we read it closely. But we can rewrite the following class to:
  1. public class NoneFluentAPI  
  2. {  
  3.     private List & lt;  
  4.     string & gt;  
  5.     languages = new List & lt;  
  6.     string & gt;  
  7.     ();  
  8.     public NoneFluentAPI()  
  9.     {  
  10.         languages.Add("English");  
  11.         languages.Add("Swedish");  
  12.     }  
  13.     private void talk(string l1, string l2)  
  14.     {  
  15.         Console.WriteLine("i am talking from " + l1 + " to " + l2);  
  16.     }  
  17.     public void Speak()  
  18.     {  
  19.         var l1 = languages[0];  
  20.         var l2 = languages[1];  
  21.         talk(l1, l2);  
  22.     }  
  23. }  
This is ‘FluentAPI’. Now if you see the ‘Speak’ function you can easily see that we have written code to call the talk method from the language ‘English’ to ‘Swedish’. So if you want to write code like this “from().to()” then the method should return the same object type.
  1. public class FluentAPI   
  2. {  
  3.     private List & lt;  
  4.     string & gt;  
  5.     languages = new List & lt;  
  6.     string & gt;  
  7.     ();  
  8.     private string _toLanguage;  
  9.     private string _fromLanguage;  
  10.     public FluentAPI()  
  11.     {  
  12.         languages.Add("English");  
  13.         languages.Add("Swedish");  
  14.     }  
  15.     private void talk()  
  16.     {  
  17.         Console.WriteLine("i am talking from " + _fromLanguage + " to " + _toLanguage);  
  18.     }  
  19.     public void Speak()  
  20.     {  
  21.         from("english").to("swedish").talk();  
  22.     }  
  23.     private FluentAPI to(string toLanguage)  
  24.     {  
  25.         _toLanguage = languages.Where(x = & gt; x.Equals(toLanguage)).FirstOrDefault();  
  26.         return this;  
  27.     }  
  28.     private FluentAPI @from(string fromLanguage)  
  29.     {  
  30.         _fromLanguage = languages.Where(x = & gt; x.Equals(fromLanguage)).FirstOrDefault();  
  31.         return this;  
  32.     }  
  33. }
Ebook Download
View all
Learn
View all