The Elegant Code I Wish I Can Write In C# 7

In my previous post Better Functional Programming Support Is Coming In C# 7  I argued that by the time you get a chance to write in C# 7 you should already be familiar with Functional Programming paradigm. But since you cannot use C# 7 at the time of writing – you should definitely consider F# for learning the concepts of Functional Programming. I hope we’ll be able to write elegant declarative-style code in C# as we do in F#.

It is hard to convince somebody to spend their time on something new without showing immediate benefits. But the benefits usually come in the form of idiomatic language features which can be overwhelming at first. I hope this post will show you immediate benefits of Functional Programming by looking at real code example and understanding the features one-by-one. I do not intend to present all of the features of F# – just enough to get you interested in Functional Programming.

Recently I have been watching Pluralsight course F# Fundamentals by Liam McLennan and stumbled upon this elegantly crafted code (fast forward to 0:46):

let rec quicksort = function
    | [] -> []
    | x :: xs ->
        let smaller = List.filter ((>) x) xs
        let larger = List.filter ((<=) x) xs
        quicksort smaller @ [x] @ quicksort larger

I was just amazed how much functionality was packed into these 6 lines of code! If you are new to Functional Programming and F# in particular, it could be hard to appreciate this code, so let’s review feature-by-feature what makes this piece of code so elegant and powerful.

If you are curious to see how quicksort implementation looks in C# – scroll to the bottom of the post.

Continue reading “The Elegant Code I Wish I Can Write In C# 7”

The Elegant Code I Wish I Can Write In C# 7

Better Functional Programming Support Is Coming In C# 7

I have recently listened to .NET Rocks! episode #1272 Looking into C# 7 with Kathleen Dollard where she mentioned that the next version of C# will have better support for tuples, immutability, records and pattern matching. You can download the episode and fast forward to 27:04 and 30:04 respectively. If you are interested, you can review the C# 7 Work List of Features (revision circa March 24 2016). You can familiarize yourself with support for these features in C# 7 right now, but since it is pretty much still work in progress, by the time it hits CTP or even release – there is a big chance it will look different.

So, what can you do in the meantime? Fortunately, Visual Studio ships with F# and you can start learning above mentioned Functional Programming concepts right now. Remember, F# is just another CLR language as C# is and many features like Generics and support for async/await came to C# from F#. When it comes to Functional Programming I hope this trend will continue.

Continue reading “Better Functional Programming Support Is Coming In C# 7”

Better Functional Programming Support Is Coming In C# 7