Chapter 4. Work Smart, Not Hard with Functional Code
Everything I’ve covered so far has been FP as intended by Microsoft’s C# team. You’ll find these features, along with examples, on the Microsoft website. In this chapter, however, I want to start being a bit more creative with C#.
I don’t know about you, but I like being lazy, or at least I don’t like wasting my time with tedious boilerplate code. One of the many wonderful things about FP is its concision, compared to imperative code.
In this chapter, I’m going to show you ways to push the functional envelope further than out-of-the-box C# will allow. You’ll also learn to implement some of the more recent functional features introduced in C# in legacy versions of the language, which will hopefully allow you to get on with your day job an awfully lot quicker.
This chapter explores a few categories of functional concepts:
Funcs in enumerables-
Funcdelegates don’t seem to get used all that much, but they’re incredibly powerful features of C#. I’ll show a few ways of using them that help extend C#’s capabilities. In this case, we’ll add them to enumerables and operate on them with LINQ expressions. Funcs as filters-
You can also use
Funcdelegates as filters—something that sits between you and the real value you’re trying to reach. You can write a few neat bits of code by using these principles. - Custom enumerables
-
I’ve discussed the
IEnumerableinterface and how cool it is before, but did you know you can break it open and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access