Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Language of Integrated Query - Part Two
WhatsApp
Asad Ali
8y
2.2
k
0
0
25
Blog
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:
Language of Integrated Query - Part One
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);
}
}
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.
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
;
}
}
.NET
C#
Fluent API
Up Next
How To Apply Cell Text & Background Color In An Excel Sheet Using EPPlus (C#) - Part Two
Ebook Download
View all
Beginning C# Object Oriented Programming
Read by 35.6k people
Download Now!
Learn
View all
Membership not found