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:
- public class NoneFluentAPI
- {
- private List & lt;
- string & gt;
- languages = new List & lt;
- string & gt;
- ();
- public NoneFluentAPI()
- {
- languages.Add("English");
- languages.Add("Swedish");
- }
- private void talk(string l1, string l2)
- {
- Console.WriteLine("i am talking from " + l1 + " to " + l2);
- }
- public void Speak()
- {
- var l1 = languages[0];
- var l2 = languages[1];
- talk(l1, l2);
- }
- }
- public class FluentAPI
- {
- private List & lt;
- string & gt;
- languages = new List & lt;
- string & gt;
- ();
- private string _toLanguage;
- private string _fromLanguage;
- public FluentAPI()
- {
- languages.Add("English");
- languages.Add("Swedish");
- }
- private void talk()
- {
- Console.WriteLine("i am talking from " + _fromLanguage + " to " + _toLanguage);
- }
- public void Speak()
- {
- from("english").to("swedish").talk();
- }
- private FluentAPI to(string toLanguage)
- {
- _toLanguage = languages.Where(x = & gt; x.Equals(toLanguage)).FirstOrDefault();
- return this;
- }
- private FluentAPI @from(string fromLanguage)
- {
- _fromLanguage = languages.Where(x = & gt; x.Equals(fromLanguage)).FirstOrDefault();
- return this;
- }
- }

Join the conversation! Your thoughts help the community grow.