{"id":546,"date":"2018-03-13T09:13:06","date_gmt":"2018-03-13T16:13:06","guid":{"rendered":"http:\/\/blog.submain.com\/?p=546"},"modified":"2020-11-02T23:11:39","modified_gmt":"2020-11-03T07:11:39","slug":"csharp-functional-programming","status":"publish","type":"post","link":"https:\/\/blog.submain.com\/csharp-functional-programming\/","title":{"rendered":"Functional Programming in C#: Map, Filter, and Reduce Your Way to Clean Code"},"content":{"rendered":"<p><span style=\"font-weight: 400;\">It&#8217;s possible that the post title above left you scratching your head. Functional programming in C#. Is that even a thing?? Well, it&#8217;s definitely a thing. Allow me to clarify.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Most people would classify C# as an object-oriented language, but it&#8217;s possible that you, as a .NET\/C# developer, have been using functional programming concepts without even knowing it.<\/span><\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" data-attachment-id=\"545\" data-permalink=\"https:\/\/blog.submain.com\/csharp-functional-programming\/c-lambda\/\" data-orig-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda.jpg?fit=1327%2C1034&amp;ssl=1\" data-orig-size=\"1327,1034\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1520549183&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;1&quot;}\" data-image-title=\"C# Lambda\" data-image-description=\"\" data-image-caption=\"\" data-medium-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda.jpg?fit=300%2C234&amp;ssl=1\" data-large-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda.jpg?fit=1024%2C798&amp;ssl=1\" class=\"wp-image-545 size-medium aligncenter\" src=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda-300x234.jpg?resize=300%2C234\" alt=\"C# Lambda logos illustrating C# Functional Programming\" width=\"300\" height=\"234\" srcset=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda.jpg?resize=300%2C234&amp;ssl=1 300w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda.jpg?resize=768%2C598&amp;ssl=1 768w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda.jpg?resize=1024%2C798&amp;ssl=1 1024w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda.jpg?w=1327&amp;ssl=1 1327w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>Make no mistake. Using functional-programming-inspired features is not the same as programming in a pure functional language, like Haskell. Or even a hybrid language but with stronger emphasis on the functional side, like F#.<\/p>\n<p><span style=\"font-weight: 400;\">However, employing functional programming concepts can improve the <a href=\"https:\/\/blog.submain.com\/5-things-responsible-poor-code-quality\/\">quality of your code<\/a>. And that&#8217;s what today&#8217;s post is about. <\/span><\/p>\n<ul>\n<li><span style=\"font-weight: 400;\">I&#8217;ll just first briefly cover the attractions of functional programming and why it makes sense to apply it even when using a so-called object-oriented language.<\/span><\/li>\n<li><span style=\"font-weight: 400;\">Then I&#8217;ll show you how you&#8217;ve already been using some functional style in your C# code, even if you&#8217;re not aware of it. <\/span><\/li>\n<li><span style=\"font-weight: 400;\">I&#8217;ll tell you how you can apply functional thinking to your code in order to make it cleaner, safer, and more expressive.<\/span><\/li>\n<\/ul>\n<p><!--more-->\n<h2><span style=\"font-weight: 400;\">C# Functional Programming: Why?<\/span><\/h2>\n<p><span style=\"font-weight: 400;\">We know the .NET framework offers some functional capabilities in the form of the LINQ extension methods, but should you use them?<\/span><\/p>\n<p><span style=\"font-weight: 400;\">To really answer this, we need to go back a step and understand the attraction of functional programming itself. <\/span><span style=\"font-weight: 400;\">The way I see it, the easiest path to start understanding the benefits of functional programming is to first understand two topics: <\/span><b>pure functions<\/b><span style=\"font-weight: 400;\"> and <\/span><b>immutable data<\/b><span style=\"font-weight: 400;\">.<\/span><\/p>\n<p><strong>Pure functions<\/strong> are functions that can only access the data they receive as arguments and, as a consequence, can&#8217;t have any side effects. Because of these properties, pure functions are predictable, easier to reason about and intrinsically testable.<\/p>\n<p><strong>Immutable data<\/strong> are just objects or data structures that, once initialized, can&#8217;t have their values changed, making them easier to reason about and automatically thread-safe.<\/p>\n<p>As a C# developer, you already employ immutability on a day-to-day basis, since several types in the .NET BCL are immutable. The <a href=\"http:\/\/blog.submain.com\/c-string-definition-examples-practices\/\">System.String<\/a> class is probably the most famous of them, but don&#8217;t forget the types related to date and time, such as <a href=\"http:\/\/blog.submain.com\/datetime-now-usage-examples\/\">DateTime<\/a>, DateTimeOffset and Timespan.<\/p>\n<p>And of course, the <a href=\"http:\/\/blog.submain.com\/c_struct\/\">structs<\/a> that represent primitive data such as int, boolean, decimal and so on are also all immutable. It wouldn&#8217;t even make sense to change the number 5, right?<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" data-attachment-id=\"777\" data-permalink=\"https:\/\/blog.submain.com\/c_struct\/c_struct_example\/\" data-orig-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example.png?fit=1548%2C1051&amp;ssl=1\" data-orig-size=\"1548,1051\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"c_struct_example\" data-image-description=\"\" data-image-caption=\"\" data-medium-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example.png?fit=300%2C204&amp;ssl=1\" data-large-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example.png?fit=1024%2C695&amp;ssl=1\" class=\"wp-image-777 size-medium aligncenter\" src=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example-300x204.png?resize=300%2C204\" alt=\"c struct example with flowers\" width=\"300\" height=\"204\" srcset=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example.png?resize=300%2C204&amp;ssl=1 300w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example.png?resize=768%2C521&amp;ssl=1 768w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example.png?resize=1024%2C695&amp;ssl=1 1024w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/11\/c_struct_example.png?w=1548&amp;ssl=1 1548w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/p>\n<h2><span style=\"font-weight: 400;\">Fundamental Functional Programming Operations and How to Perform Them Using C#<\/span><\/h2>\n<p>With the <em>what<\/em> and <em>why<\/em> of functional programming out of the way, it&#8217;s time to get to the <em>how<\/em>.<\/p>\n<p>I&#8217;ll be covering three fundamental functions: map, filter, and reduce. I&#8217;ll start by showing some use cases, then I&#8217;ll show a traditional, procedural way of solving the problem. And finally, I&#8217;ll present the functional way.<\/p>\n<h2><span style=\"font-weight: 400;\">C# Map<\/span><\/h2>\n<p><span style=\"font-weight: 400;\">In simple terms, the &#8216;map&#8217; operation takes a <a href=\"http:\/\/blog.submain.com\/c-list-definition-examples-best-practices-pitfalls\/\">sequence<\/a> of items, applies some transformation to each one of those items, and returns a new sequence with the resulting items. Let&#8217;s see some examples.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Suppose you wrote the following code, due to a customer&#8217;s demand:<\/span><\/p>\n<pre class=\"lang:c# decode:true \">static void AddThreeToEachElement(int[] arr)\n{\n    for (var i = 0; i &lt; arr.Length; i++)\n    {\n       arr[i] += 3;\n    }\n}<\/pre>\n<p><span style=\"font-weight: 400;\">It&#8217;s a function that adds three to each element of the given <a href=\"https:\/\/blog.submain.com\/c-array\/\">array<\/a> of integers. Pretty straightforward.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Now a request for a new function comes in. This time, it should add five to each element in an array. Ignoring the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Rule_of_three_(computer_programming)\">rule of three,<\/a> you jump right ahead into a generalized version, parameterizing the number to be added:<\/span><\/p>\n<pre class=\"lang:c# decode:true \">static void AddNumberToEachElement(int[] arr, int n)\n{\n   for (var i = 0; i &lt; arr.Length; i++)\n   {\n        arr[i] += n;\n   }\n}<\/pre>\n<p><span style=\"font-weight: 400;\">Then yet another request comes in. Now you must write a function that will multiply each element of the given array by, let&#8217;s say, three. I won&#8217;t add the code sample now because I&#8217;m sure you&#8217;ve got the picture. <\/span><\/p>\n<p><span style=\"font-weight: 400;\">By now, you should know better than to hardcode the number, so you&#8217;d probably jump ahead to a general version right away. Even then, some duplication would still exist: the loop itself. <\/span><\/p>\n<p><span style=\"font-weight: 400;\">Hmm&#8230;what if you could keep just the loop and instead parameterize the action to be applied on each item?<br \/>\n<\/span><\/p>\n<h3><span style=\"font-weight: 400;\">The Functional Way<\/span><\/h3>\n<p><span style=\"font-weight: 400;\">Take into consideration what you&#8217;ve just read about pure functions&#8212;and also your previous knowledge of <\/span><a href=\"https:\/\/blog.submain.com\/coding-best-practices-short-time\/\"><span style=\"font-weight: 400;\">programming best practices<\/span><\/a><span style=\"font-weight: 400;\"> in general&#8212;and think of ways the code could be improved.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">From my perspective, the main problems are<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\"><strong>The code is too specific<\/strong>. It can&#8217;t be easily changed to accommodate other transformations being applied to the array elements. It just performs a sum, and that&#8217;s it.<\/span><\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\"><strong>Too much boilerplate<\/strong>. Look at the previous sample again. Count the lines. There are seven, of which only one really concerns itself with carrying through the business logic of the method.<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">How would the functional way improve on this? That&#8217;s the way I&#8217;d write the first example in F#, for instance:<\/span><\/p>\n<pre class=\"lang:haskell decode:true \">let result = Seq.map (fun x -&gt; x + 3) numbers<\/pre>\n<p><span style=\"font-weight: 400;\">I&#8217;m assuming here that &#8220;numbers&#8221; is a sequence of integers I&#8217;ve got somehow. Then I use the map function on the Seq module, passing the sequence as a parameter, along with a function that takes an int and adds three to it.<br \/>\n\n<\/span><\/p>\n<h3><span style=\"font-weight: 400;\">The Functional Way, .NET\/C# Flavor<\/span><\/h3>\n<p><span style=\"font-weight: 400;\">.NET implements the map operation in the form of the &#8216;Select&#8217; LINQ extension method. So you could rewrite the F# example above like this:<\/span><\/p>\n<pre class=\"lang:c# decode:true\">var result = numbers.Select(x =&gt; x + 3);<\/pre>\n<p><span style=\"font-weight: 400;\">One important point that needs explaining is that the type of the resulting sequence doesn&#8217;t need to match the type of the source sequence. <\/span><\/p>\n<p><span style=\"font-weight: 400;\">Do you have a list of &#8216;Employee&#8217; and need a sequence of ints (containing, for instance, their IDs)? Easy peasy:<\/span><\/p>\n<pre class=\"lang:c# decode:true\">List&lt;Employee&gt; employees = EmployeeRepository.All();\nIEnumerable&lt;int&gt; ids = employees.Select(x =&gt; x.Id);<\/pre>\n<p><span style=\"color: #333333; font-size: 26px;\">C# Filter<\/span><\/p>\n<p><span style=\"font-weight: 400;\">I think filter is, hands down, the easiest operation of the bunch. It has a very intuitive name, and the need for filtering stuff is so common in programming that I bet you correctly guessed what it is just by its name (if you didn&#8217;t know it already).<\/span><\/p>\n<p><span style=\"font-weight: 400;\">For the sake of completeness, though, let&#8217;s define it. The filter operation&#8230;wait for it&#8230;filters a sequence, returning a new sequence containing just the items approved by some criteria.<\/span><\/p>\n<h3><span style=\"font-weight: 400;\">The Imperative Way<\/span><\/h3>\n<p><span style=\"font-weight: 400;\">Since we&#8217;ve used employees in the previous section, let&#8217;s keep within the theme. Let&#8217;s say you need to come up with a list of the employees who have used at least three sick days.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">In a more procedural style, you&#8217;d maybe write something along the following lines:<\/span><\/p>\n<pre class=\"lang:default decode:true\">public static List&lt;Employee&gt; GetEmployeesWithAtLeastNSickdays(List&lt;Employee&gt; employees, int number)\n{\n    List&lt;Employee&gt; result = new List&lt;Employee&gt;();\n    \n    foreach (var e in employees)\n    {\n        if (e.Sickdays &gt;= number)\n     {\n      result.Add(e);\n     } \n    }\n    \n    return result;\n}<\/pre>\n<p><span style=\"font-weight: 400;\">I wouldn&#8217;t say there&#8217;s something <em>definitely<\/em> wrong with this code. The method&#8217;s name is a bit too long, but it&#8217;s very descriptive. The code does what it promises. And it&#8217;s readable enough.<\/span><\/p>\n<p>But similarly to the previous section, we can make the argument that the code is too noisy. We can say that, essentially, the only line that does something domain related is the <em>if<\/em> test. All the other lines are basically boilerplate-y infrastructure code.<\/p>\n<p>Can a functional approach help us here?<\/p>\n<h3><span style=\"font-weight: 400;\">The Functional Way<\/span><\/h3>\n<p>Let&#8217;s rewrite the method above by using LINQ:<\/p>\n<pre class=\"lang:default decode:true\">public static List&lt;Employee&gt; GetEmployeesWithAtLeastNSickdays(List&lt;Employee&gt; employees, int number)\n{\n    return employees.Where(x =&gt; x.SickDays &gt;= n).ToList();\n}<\/pre>\n<p>Here we use the &#8220;Where&#8221; extension method, passing the filtering criterium as a delegate. To be honest, the outer method became not very useful since it just delegates the work. In real life, I&#8217;d get rid of it.<\/p>\n<h2><span style=\"font-weight: 400;\">C# Reduce<\/span><\/h2>\n<p>Reduce is often the one many developers have some difficulty understanding. But it isn&#8217;t hard at all.<\/p>\n<p>Think of it like this: you have a sequence of something, and you also have a function that takes two of these &#8220;somethings&#8221; and returns one, after doing some processing.<\/p>\n<p>Then you start applying the function. You apply it to the first two elements in the sequence and store the result. Then you apply it again to the result and the third element. Then you do it again to the result and the fourth item, and so forth.<\/p>\n<p>The classical example of reduce is adding up a list of numbers, so that&#8217;s exactly what we&#8217;re going to do in our example.<\/p>\n<h3><span style=\"font-weight: 400;\">The Imperative Way<\/span><\/h3>\n<p>So, suppose we&#8217;re to sum a bunch of integers. We could do it like this:<\/p>\n<pre class=\"lang:default decode:true \">public int Sum(IEnumerable&lt;int&gt; numbers)\n{\n    var result = 0;\n    foreach (var number in numbers)\n    {\n        result += number;\n    }\n\n    return result;\n}<\/pre>\n<p>At this point, you&#8217;re probably familiar with what I have to say about this code: it isn&#8217;t necessarily wrong, but it&#8217;s inflexible and noisy. Can functional programming save us?<\/p>\n<h3><span style=\"font-weight: 400;\">The Functional Way<\/span><\/h3>\n<p>In .NET\/C#, the &#8220;Reduce&#8221; operation assumes the form of the &#8220;Aggregate&#8221; extension method. This time, I&#8217;ll just get rid of the enclosing method and write the LINQ solution right away:<\/p>\n<pre class=\"lang:default decode:true\">var sum = number.Aggregate((x, y) =&gt; x + y);<\/pre>\n<p>Things look a little bit more complex here, but don&#8217;t get scared. In this case, we&#8217;re just passing a function that takes two parameters, instead of one, like in the previous examples. It has to be that way since the function must be applied to two elements of the sequence each time.<\/p>\n<p>But as it turns out, there&#8217;s an even easier way of solving this particular problem (adding a bunch of numbers). Since summing a sequence of numbers is such a common use case, there&#8217;s a dedicated method to do just that. It&#8217;s called, not surprisingly, &#8220;Sum&#8221;:<\/p>\n<pre class=\"lang:default decode:true \">var sum = numbers.Sum();<\/pre>\n<p>What&#8217;s &#8220;Aggregate&#8221; good for, then? Well, adding a list of integers is just one of the applications for reduce, but you&#8217;re not in any way restricted to only that. You can use it with any binary operation, such as concatenating strings or summing custom types.<\/p>\n<h2>The Verdict: Is the Functional Approach Better?<\/h2>\n<p>After these examples, you might be wondering if the &#8220;functional&#8221; way is any better? It&#8217;d be extremely hard to define what &#8220;better&#8221; is, so I won&#8217;t even bother. Let&#8217;s consider another criterion: readability.<\/p>\n<p>Though we know that code readability <a href=\"https:\/\/blog.submain.com\/evaluate-code-readability\/\">can also be highly subjective,<\/a>?I&#8217;d say that yes, the functional examples are more readable. Suppose we need to retrieve and sum all the salaries from employees with more than five years of company time. We could easily do that by writing a loop, in which we&#8217;d test the condition and accumulate the salary if the test turned out true.<\/p>\n<p>Or we could just write this:<\/p>\n<pre class=\"lang:default decode:true \">var sum = employees.Where(x =&gt; x.CompanyTimeInYears &gt; 5).Select(x =&gt; x.Salary).Sum();<\/pre>\n<p>I honestly believe this line to be more readable (and generally better) than the procedural approach. It&#8217;s more declarative; it shows the intention of <strong>what<\/strong> we&#8217;re trying to get done without being too concerned with the <strong>how<\/strong>.<\/p>\n<p>It almost reads like natural language: &#8220;The list of employees where their time in the company is greater than five years, select their salary and sum them&#8221;.<\/p>\n<h2>Add Some Functional Spice to Make Your Code Tastier<\/h2>\n<p>Many people use LINQ for years without even realizing they&#8217;re using functional programming concepts. I take this as proof that functional programming isn&#8217;t beyond the capabilities of the enterprise developer who lacks a strong background in math.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" data-attachment-id=\"500\" data-permalink=\"https:\/\/blog.submain.com\/evaluate-code-readability\/fig-newton-stack-with-one-facing-the-wrong-way\/\" data-orig-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way.jpg?fit=1545%2C1160&amp;ssl=1\" data-orig-size=\"1545,1160\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;1516375540&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;1&quot;}\" data-image-title=\"Fig Newton Stack with One Facing the Wrong Way\" data-image-description=\"\" data-image-caption=\"\" data-medium-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way.jpg?fit=300%2C225&amp;ssl=1\" data-large-file=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way.jpg?fit=1024%2C769&amp;ssl=1\" class=\"wp-image-500 alignright\" src=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way-1024x769.jpg?resize=508%2C382\" alt=\"Fig Newton Stack with One Facing the Wrong Way\" width=\"508\" height=\"382\" srcset=\"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way.jpg?resize=1024%2C769&amp;ssl=1 1024w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way.jpg?resize=300%2C225&amp;ssl=1 300w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way.jpg?resize=768%2C577&amp;ssl=1 768w, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/01\/Fig-Newton-Stack-with-One-Facing-the-Wrong-Way.jpg?w=1545&amp;ssl=1 1545w\" sizes=\"auto, (max-width: 508px) 100vw, 508px\" \/>Some of the concepts presented here are neither new nor restricted to functional programming. The benefits of distinguishing between functions that produce side effects from those that don&#8217;t is the basis of principles like <a href=\"https:\/\/en.wikipedia.org\/wiki\/Command%E2%80%93query_separation\">command-query separation (CQS)<\/a>, for instance.<\/p>\n<p>By the way, it bears repeating: employing functional-like features in a language like C# isn&#8217;t really the same as using a more full-fledged functional language.<\/p>\n<p>For example, at first sight, F#&#8217;s pattern matching may not look a whole lot different than C#&#8217;s <a href=\"http:\/\/blog.submain.com\/c-switch-statement-beware\/\">switch<\/a>. But when using pattern matching, F#&#8217;s compiler will give you a warning if you forget to match some option.<\/p>\n\nAnd since <a href=\"https:\/\/blog.submain.com\/treat-warnings-errors\/\">you should treat warning as errors<\/a>, that&#8217;s a handy feature to avoid bugs that would otherwise creep in to maybe be caught by unit tests afterwards.<\/p>\n<p><span style=\"font-weight: 400;\">Haskell, as a pure functional language, enforces the separation between code that produces side effects and code that doesn&#8217;t, so you&#8217;re basically forced to design your code in such a way that takes the maximum advantage of pure functions.<\/span><\/p>\n<p>The goal of this post was not to teach you functional programming. This is honestly beyond my capabilities, as I&#8217;m still studying it myself. And besides, there are <a href=\"http:\/\/fsharpforfunandprofit.com\">awesome resources for that purpose if you want to learn more<\/a>.<\/p>\n<p>Instead, what I wanted here is to give you a little taste of what a functional style can do for your code, which is to make it more expressive, concise, and declarative. Now it&#8217;s up to you to try to apply the functional mindset to the code you write.<\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>It&#8217;s possible that the post title above left you scratching your head. Functional programming in C#. Is that even a thing?? Well, it&#8217;s definitely a thing. Allow me to clarify. Most people would classify C# as an object-oriented language, but it&#8217;s possible that you, as a .NET\/C# developer, have been using functional programming concepts without even knowing it. Make no mistake. Using functional-programming-inspired features is not the same as programming in a pure functional language, like Haskell. Or even a hybrid language but with stronger emphasis on the functional side, like F#. However, employing functional programming concepts can improve the quality of your code. And that&#8217;s what today&#8217;s post is about. I&#8217;ll just first briefly cover the attractions of functional programming and why it makes sense to apply it even when using a so-called object-oriented language. Then I&#8217;ll show you how you&#8217;ve already been using some functional style in your&#8230;<\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[2,1814,7],"tags":[],"class_list":["post-546","post","type-post","status-publish","format-standard","hentry","category-articles","category-carlosschults","category-codequality"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v15.0 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Functional Programming in C#: Map, Filter, and Reduce<\/title>\n<meta name=\"description\" content=\"You can do functional programming in C#. Learn C# Map, Filter, and Reduce in order to help you write cleaner code that&#039;s easier to reason about.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blog.submain.com\/csharp-functional-programming\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Functional Programming in C#: Map, Filter, and Reduce\" \/>\n<meta property=\"og:description\" content=\"You can do functional programming in C#. Learn C# Map, Filter, and Reduce in order to help you write cleaner code that&#039;s easier to reason about.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blog.submain.com\/csharp-functional-programming\/\" \/>\n<meta property=\"og:site_name\" content=\"Software Quality Blog - SubMain Software\" \/>\n<meta property=\"article:published_time\" content=\"2018-03-13T16:13:06+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-11-03T07:11:39+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda-300x234.jpg\" \/>\n<meta name=\"twitter:card\" content=\"summary\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/blog.submain.com\/#website\",\"url\":\"https:\/\/blog.submain.com\/\",\"name\":\"Software Quality Blog - SubMain Software\",\"description\":\"Code Quality Tools, Automated Code Review and Refactoring\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/blog.submain.com\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/blog.submain.com\/csharp-functional-programming\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"http:\/\/blog.submain.com\/wp-content\/uploads\/2018\/03\/C-Lambda-300x234.jpg\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/blog.submain.com\/csharp-functional-programming\/#webpage\",\"url\":\"https:\/\/blog.submain.com\/csharp-functional-programming\/\",\"name\":\"Functional Programming in C#: Map, Filter, and Reduce\",\"isPartOf\":{\"@id\":\"https:\/\/blog.submain.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/blog.submain.com\/csharp-functional-programming\/#primaryimage\"},\"datePublished\":\"2018-03-13T16:13:06+00:00\",\"dateModified\":\"2020-11-03T07:11:39+00:00\",\"author\":{\"@id\":\"https:\/\/blog.submain.com\/#\/schema\/person\/cb6edf23222435414660528ab7b2fcfa\"},\"description\":\"You can do functional programming in C#. Learn C# Map, Filter, and Reduce in order to help you write cleaner code that's easier to reason about.\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/blog.submain.com\/csharp-functional-programming\/\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/blog.submain.com\/#\/schema\/person\/cb6edf23222435414660528ab7b2fcfa\",\"name\":\"Carlos Schults\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/blog.submain.com\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g\",\"caption\":\"Carlos Schults\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","jetpack_shortlink":"https:\/\/wp.me\/p8R7uj-8O","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":920,"url":"https:\/\/blog.submain.com\/3-most-common-c-data-types-explanations-examples\/","url_meta":{"origin":546,"position":0},"title":"The 3 Most Common C# Data Types: Explanations and Examples","author":"Carlos Schults","date":"July 9, 2019","format":false,"excerpt":"If you're a regular reader of the SubMain blog, you'll know that we often publish posts about fundamental concepts of the C# language. Today's post adds yet another chapter to this ongoing series. The topic we'll cover is, in fact, as fundamental as it can get: C# data types. As\u2026","rel":"","context":"In &quot;Articles&quot;","block_context":{"text":"Articles","link":"https:\/\/blog.submain.com\/category\/articles\/"},"img":{"alt_text":"Gold medal","src":"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2019\/07\/Gold_medal-686x1024.jpg?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":147,"url":"https:\/\/blog.submain.com\/you-can-use-ghostdocs-document-this-with-javascript\/","url_meta":{"origin":546,"position":1},"title":"You Can Use GhostDoc&#8217;s Document This with JavaScript","author":"Carlos Schults","date":"February 6, 2017","format":false,"excerpt":"If you haven't lived in a techie cave the last 10 years, you've probably noticed JavaScript's rise to prominence.? Actually, forget prominence.? JavaScript has risen to command consideration as today's lingua franca of modern software development. I find it sort of surreal to contemplate that, given my own backstory.? Years\u2026","rel":"","context":"In &quot;Articles&quot;","block_context":{"text":"Articles","link":"https:\/\/blog.submain.com\/category\/articles\/"},"img":{"alt_text":"blog-ghostdoc-with-javacript-01","src":"https:\/\/i0.wp.com\/submain.com\/blog\/content\/binary\/Open-Live-Writer\/You-Can-Use-GhostDocs-Document-This-with_D720\/blog-ghostdoc-with-javacript-01_3.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/submain.com\/blog\/content\/binary\/Open-Live-Writer\/You-Can-Use-GhostDocs-Document-This-with_D720\/blog-ghostdoc-with-javacript-01_3.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/submain.com\/blog\/content\/binary\/Open-Live-Writer\/You-Can-Use-GhostDocs-Document-This-with_D720\/blog-ghostdoc-with-javacript-01_3.png?resize=525%2C300 1.5x, https:\/\/i0.wp.com\/submain.com\/blog\/content\/binary\/Open-Live-Writer\/You-Can-Use-GhostDocs-Document-This-with_D720\/blog-ghostdoc-with-javacript-01_3.png?resize=700%2C400 2x"},"classes":[]},{"id":538,"url":"https:\/\/blog.submain.com\/visual-basic-dead\/","url_meta":{"origin":546,"position":2},"title":"Is Visual Basic Dead?","author":"Carlos Schults","date":"February 27, 2018","format":false,"excerpt":"Is Visual Basic dead?? Yup.? Wow, hey, that might have been the easiest blog post I've ever written.? See ya next week! Oh, wait.? You probably want me to justify this claim somehow, don't you?? And then you probably want me to add support for the argument, nuance in position,\u2026","rel":"","context":"In &quot;Articles&quot;","block_context":{"text":"Articles","link":"https:\/\/blog.submain.com\/category\/articles\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/02\/Is-Visual-Basic-Dead.jpg?fit=1200%2C930&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/02\/Is-Visual-Basic-Dead.jpg?fit=1200%2C930&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/02\/Is-Visual-Basic-Dead.jpg?fit=1200%2C930&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/02\/Is-Visual-Basic-Dead.jpg?fit=1200%2C930&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2018\/02\/Is-Visual-Basic-Dead.jpg?fit=1200%2C930&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":174,"url":"https:\/\/blog.submain.com\/webcast-asynchronous-programming-demystified-jan-14th\/","url_meta":{"origin":546,"position":3},"title":"Webcast: Asynchronous Programming Demystified &#8211; Jan 14th","author":"Carlos Schults","date":"January 6, 2015","format":false,"excerpt":"Recording of the webcast, slides and demo code have been posted to the website - watch it here Enjoy the recording, and please let us know how we can help! Featuring Stephen Cleary, Microsoft MVP \u00a0 Date: Wednesday, January 14th, 2015 \u00a0 Time: 10:00 am PST \/ 1:00 pm EST\u2026","rel":"","context":"In &quot;CodeIt.Right&quot;","block_context":{"text":"CodeIt.Right","link":"https:\/\/blog.submain.com\/category\/codeit-right\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/submain.com\/webcasts\/asynchronous-programming-demystified\/webcast-asynchronous-programming-demystified-invite-300x239.png?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":480,"url":"https:\/\/blog.submain.com\/code-review-vs-pair-programming-2\/","url_meta":{"origin":546,"position":4},"title":"Code Review vs Pair-Programming: Which One Should Your Team Pick?","author":"Carlos Schults","date":"January 3, 2018","format":false,"excerpt":"Some weeks ago, I was browsing Twitter when I saw this: Pair Programming > Code Review ? Rafael Ponte (@rponte) November 19, 2017 This prompted a brief discussion between the author and me. He made good arguments, but I left unconvinced that pair programming was the obvious winner. As someone\u2026","rel":"","context":"In &quot;Articles&quot;","block_context":{"text":"Articles","link":"https:\/\/blog.submain.com\/category\/articles\/"},"img":{"alt_text":"Code review vs pair programming (as shown here): which should your team pick?","src":"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2017\/12\/Two-Men-Looking-at-Computer-Screens-e1560966114905.jpg?fit=940%2C455&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2017\/12\/Two-Men-Looking-at-Computer-Screens-e1560966114905.jpg?fit=940%2C455&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2017\/12\/Two-Men-Looking-at-Computer-Screens-e1560966114905.jpg?fit=940%2C455&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2017\/12\/Two-Men-Looking-at-Computer-Screens-e1560966114905.jpg?fit=940%2C455&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":870,"url":"https:\/\/blog.submain.com\/c-operators-a-detailed-guide\/","url_meta":{"origin":546,"position":5},"title":"C# Operators: A Detailed Guide to All Of Them","author":"Carlos Schults","date":"September 16, 2019","format":false,"excerpt":"Every programming language has operators. Operators are the components of the language that, well, operate on variables mostly. Most C# operators are symbols such as % and ??. And some are words, like async and is. In this guide, you'll see all of them, including an example of each one.\u2026","rel":"","context":"In &quot;Articles&quot;","block_context":{"text":"Articles","link":"https:\/\/blog.submain.com\/category\/articles\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/blog.submain.com\/wp-content\/uploads\/2019\/04\/You%E2%80%99ll-end-up-with-fewer-errors-in-your-code..png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]}],"_links":{"self":[{"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/posts\/546","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/comments?post=546"}],"version-history":[{"count":5,"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/posts\/546\/revisions"}],"predecessor-version":[{"id":1080,"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/posts\/546\/revisions\/1080"}],"wp:attachment":[{"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/media?parent=546"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/categories?post=546"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.submain.com\/wp-json\/wp\/v2\/tags?post=546"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}