Software Development

Crashing Visual Studio 2015 with Explicit Interface Implementations

In F#, all interface implementations are always explicit meaning that the interface methods will only be accessible when treating the implementing type as that interface. This makes sense in F# because it removes all ambiguity around what the method applies to. Explicit implementations also force us into coding to the interface because other miscellaneous members of the implementing type aren’t exposed through the interface definition. For these reasons I’ve been hooked on explicit interface implementation and even use it almost exclusively with great success in my C# applications.

Imagine my surprise then when Visual Studio 2015 crashed when I tried to rename an explicitly implemented interface method! The first time it happened I figured it was probably just Visual Studio misbehaving but when I reopened the solution and tried again the same thing happened! Clearly there was something more to this.

RefactorCrash

Renaming an explicitly implemented interface method causes Visual Studio 2015 to crash.

Hoping that I’d perhaps stumbled upon something that was fixed and included in Update 1, I upgraded Visual Studio and tried again. The crash still occurred.

To narrow down the issue I created a brand new solution with a console application. Within the new project I defined a simple interface with a single method and explicitly implemented it in a class. At this point I attempted to rename the method and it worked as expected. I then tried renaming the interface method directly on the interface and that also worked as expected. Then I figured that it must have something to do with how the interface was being used so I created an instance of the class, converted it to the interface, and tried the rename again and it was successful. Finally, I added a line to invoke the interface method and tried the rename one more time. Oddly, it again worked as expected.

On a whim I decided to move the interface and implementation into a separate project. After adding the project reference and doing a test build I again tried to rename the method and sure enough, Visual Studio crashed. I’ve since played with a few different combinations and have been able to successfully recreate the crash as long as the interface is defined in a separate assembly and I tried renaming the method via the explicit implementation.

In summary, it appears that in order to recreate this crash the following conditions must be met:

  • Interface must be explicitly implemented
  • Interface must be defined in a separate assembly than where it’s used
  • Rename must be attempted against the explicit implementation
  • Interface method must be invoked – simply creating an instance won’t cause the crash.

I’ve submitted the issue to Microsoft on Connect but this seems like such an edge case I’d be surprised to see a fix anytime soon. In the mean time, if this is something you encounter you can safely rename the method on the interface itself or at the call site; neither of those seemed to be an issue.

If you’d like to mess around with this issue on your own, I’ve shared my sample project on GitHub.

Advertisement

Reshaping Data with R

I was scrolling through my Facebook feed yesterday afternoon and one post stood out among the endless stream of memes. A friend had a data transformation question! She said:

Data handling question! I fairly frequently receive “tall” client data that needs to be flattened to be functional. So for example, Jane Doe may have twelve rows of data, each for a different month of performance, and I need to compress this so that her monthly performance displays on one row only, with columns for each month. Anyone know of a relatively painless way to do this quickly? I’ve been sending files like this to our data guy to flatten, but I’d love to be able to do it myself.

I immediately thought: “Hey! This sounds like a job for R!” Unfortunately, my R knowledge is limited to knowing that it’s a statistical programming language so in the interests of both helping out my friend and getting a little experience with something I’ve wanted to play around with, I set out to see how easy – or difficult – this task would be in R. It turned out to be quite simple.

Naturally I didn’t even have the R environment installed on my laptop so I obtained the installer from the R project site. Once it installed, I was off.

I started by creating a CSV that would simulate the scenario she described. My highly contrived data looked like this:

Name Month Value
Jane Doe January 10
Jane Doe February 11
Jane Doe March 5
Jane Doe April 8
Jane Doe May 10
Jane Doe June 15
Jane Doe July 12
Jane Doe August 8
Jane Doe September 11
Jane Doe October 7
Jane Doe November 9
Jane Doe December 13
John Doe January 5
John Doe February 3
John Doe March 8
John Doe April 7
John Doe May 6
John Doe June 5
John Doe July 5
John Doe August 8
John Doe September 4
John Doe October 2
John Doe November 5
John Doe December 9

With some source data ready it was time to move onto reading the data. It turns out that R has some nice capabilities for reading CSV files so I loaded it as follows:

df <- read.csv(file="C:\\Dev\\Data.csv", header = TRUE)

Here we’re reading the CSV and binding the resulting data frame to df.

Next, I needed to transform the data. After a bit of research I found there are a few ways to do this but using the reshape2 package seemed like the easiest approach. I installed the package and referenced it in my script.

library(reshape2)

Reshape2 is designed to transform data between wide and tall formats. Its functionality is built around two complementary functions; melt and cast. The melt function handles transforming wide data to a tall format whereas cast transforms tall data into a wide format. Given that my friend was trying to convert from tall to wide, cast was clearly the one I needed.

The cast function comes in two flavors: dcast and acast which result in either a new data frame or a vector/matrix/array respectively. To (hopefully) keep things simple I opted for the data frame approach and used dcast for this transformation.

To transform the data I simply needed to apply the dcast function to the CSV data. That is done like this:

pivot = dcast(df, Name~Month)

Here, the first argument df is our CSV data. The second argument specifies the column names that will serve as the axis for the transformation.

Finally I needed to persist the data. Just as with loading, R can easily write a CSV file.

write.csv(pivot, file="C:\\Dev\\Pivot.csv")

Finally, I executed the script and here’s the result:

Name April August December February January July June March May November October September
1 Jane Doe 8 8 13 11 10 12 15 5 10 9 7 11
2 John Doe 7 8 9 3 5 5 5 8 6 5 2 4


Although the data was transformed correctly it wasn’t quite what I expected to see. There are two problems here:

  1. The row numbers are included
  2. The months are alphabetized

It turns out that both of these problems are easy to solve. Let’s first handle eliminating the row numbers.

To exclude the row numbers from the resulting CSV we simply need to set the optional row.names parameter to FALSE in the write.csv function call.

write.csv(pivot, file="C:\\Dev\\Pivot.csv", row.names=FALSE)

Fixing the column order isn’t quite as simple but it’s really not bad either; we simply need to manually specify the column order by treating the frame as a vector and using the concatenation function to specify the new order.

In the interest of space I used the index approach but it’s also acceptable to use the column names instead.

pivot = dcast(df, Name~Month)[,c(1,6,5,9,2,10,8,7,3,13,12,11,4)]

Putting this all together, the final script now looks like this:

library(reshape2)

df <- read.csv(file="C:\\Dev\\Data.csv", header = TRUE)

pivot = dcast(df, Name~Month)[,c(1,6,5,9,2,10,8,7,3,13,12,11,4)]

write.csv(pivot, file="C:\\Dev\\Pivot.csv", row.names=FALSE)

Run this version and you’ll get the following, cleaned up result:

Name January February March April May June July August September October November December
Jane Doe 10 11 5 8 10 15 12 8 11 7 9 13
John Doe 5 3 8 7 6 5 5 8 4 2 5 9

So I ask this of my friends and readers that are more versed in R than I. Is this the preferred way to handle such transformations? If not, how would you approach it?

Upcoming Events

I have a few speaking engagements coming up that I wanted to let you know about. First, I’ll be visiting Cincinnati, Ohio on July 28 for CINNUG. Then, on August 20 I’ll be making the quick trip down to Louisville, Kentucky for the Louisville .NET Meetup Group.

For both of these events I’ll be speaking about Functional .NET. In this talk we’ll explore some of the ways that we can utilize higher-order static methods and extension methods to enable the rough equivalent of some functional patterns in C#. As a bonus, I’ll also be giving away a copy of my book, The Book of F# at each of these events!

If you’re in the Cincinnati or Louisville areas and interested in learning how applying functional techniques in C# can improve your overall code quality, be sure to join us! As always, check the respective group pages for up-to-date logistics. I hope to see you there!

My 5 Favorite C# 6.0 Features

With C# 6 nearly upon us I thought it would be a good time to revisit some of the upcoming language features. A lot has changed since I last wrote about the proposed new features so let’s take a look at what’s ahead.

I think it’s fair to say that have mixed feelings about this release as far as language features go especially since many of my favorite proposed features were cut. I was particularly sad to see primary constructors go because of how much waste is involved with explicitly creating a constructor, especially when compared to the same activity in F#. Similarly, declaration expressions would have nearly fixed another of my least favorite things in C# – declaring variables to hold out parameters outside of the block where they’re used. Being able to declare those variables inline would have been a welcome improvement. That said, I think there are some nice additions to the language. Here’s a rundown of my top five favorite C# 6.0 language features in no particular order.

Auto-Property Initialization Enhancements

The auto-property initialization enhancements give us a convenient way to define an auto-property and set its initial value without necessarily having to also wire up a constructor. Here’s a trivial example where the Radius property on a Circle class is initialized to zero:

public class Circle
{
    public int Radius { get; set; } = 0;
}

The same syntax is available for auto-properties with private setters like this:

public class Circle
{
    public int Radius { get; private set; } = 0;
}

So we saved a few keystrokes by not needing a constructor. Big deal, right? If this were the end of the story, this feature definitely wouldn’t have made this list but there’s one more variant that I’m really excited about: getter-only auto-properties. Here’s the same class revised to use a getter-only auto-property:

public class Circle
{
    public int Radius { get; } = 0;
}

Syntactically these don’t differ much but behind the scenes is a different story. What getter-only auto-properties give us is true immutability and that’s why I’m so excited about this feature. When using the private setter version, the class is immutable from the outside but anything inside the class can still change those values. For instance,

in the private setter version it would be perfectly valid to have a Resize method that could change Radius. Getter-only auto-properties are different in that the compiler generates a readonly backing field making it impossible to change the value from anywhere outside of the constructor. This is important because now, when combined with a constructor we have a fairly convenient mechanism for creating immutable objects.

public class Circle
{
    public int Radius { get; }

    public Circle(int radius)
    {
        Radius = radius;
    }
}

Now this isn’t quite as terse as F#’s record types but by guiding developers toward building immutable types, it’s definitely a step in the right direction.

Using Static

Using static allows us to access static methods as though they were globally available without specifying the class name. This is largely a convenience feature but when applied sparingly it can not only simplify code but also make the intent more apparent. For instance, a method to find the distance between two points might look like this:

public double FindDistance(Point other)
{
    return Math.Sqrt(Math.Pow(this.X - other.X, 2) + Math.Pow(this.Y - other.Y, 2));
}

Although this is a simple example, the intent of the code is easily lost because the formula is broken up by references to the Math object. To solve this, C# 6 lets us make static members of a type available without the type prefix via new using static directives. Here’s how we’d include System.Math’s static methods:

using static System.Math;

Now that System.Math is imported and its methods are available in the source file we can then remove the references to Math from the remaining code which leaves us with this:

public double FindDistance(Point other)
{
    return Sqrt(Pow(this.X - other.X, 2) + Pow(this.Y - other.Y, 2));
}

Without the references to Math, the formula becomes a bit clearer.

A side-benefit of using static is that we’re not limited to static methods – if it’s static, we can use it. For example, you could include a using static directive for System.Drawing.Color to avoid having to prefix every reference to a color with the type name.

Expression-Bodied Members

Expression-bodied members easily count as one of my favorite C# 6 feature because they elevate the importance of expressions within the traditionally statement-based language by allowing us to supply method, operator, and read-only property bodies with a lambda expression-like syntax. For instance, we could define a ToString method on our Circle class from earlier as follows:

public override string ToString() => $"Radius: {Radius}";

Note that the above snippet uses another new feature: string interpolation. We’ll cover that shortly.

At first glance it may appear that this feature is somewhat limited because C#’s statement-based nature automatically reduces the list of things that can serve as the member body. For this reason I was sad to see the semicolon operator removed from C# 6 because it would have added quite a bit of power to expression-bodied members. Unfortunately the semicolon operator really just traded one syntax for an only slightly improved syntax.

If expression-bodied members are so limited why are they on this list? Keep in mind that any expression can be used as the body. As such we can easily extend the power of expression-bodied members by programming in a more functional style.

Consider a method to read a text file from a stream. By using the Disposable.Using method defined in the linked functional article, we can reduce the body to a single expression as follows:

public static string ReadFile(string fileName) =>
    Disposable.Using(
        () => System.IO.File.OpenText(fileName),
        r => r.ReadToEnd());

Without taking advantage of C#’s functional features, such an expression wouldn’t be possible but in doing so we greatly extend the capabilities of this feature. Essentially, whenever the property or method body would be reduced to a return statement by using the described approach, you can use an expression-bodied member instead.

String Interpolation

Ahhh, string interpolation. When I first learned that this feature would be included in C# 6 I had flashbacks to the early days of my career when I was maintaining some Perl CGI scripts. String interpolation was one of those things that I always wondered why it wasn’t part of C# but String.Format, while moderately annoying, always worked well enough that it wasn’t particularly a problem. Thanks to a new string literal syntax, C# 6 will let us define format strings without explicitly calling String.Format by allowing us to include identifiers and expressions within holes in the literal. The compiler will detect the string and handle the formatting as appropriate by filling the holes with the appropriate value.

To define an interpolated string, simply prefix a string literal with a dollar sign ($). Anything that should be injected into the string is simply included inline in the literal and enclosed in curly braces just as with String.Format. We already saw an example of string interpolation but let’s take another look at the example:

public override string ToString() => $"Radius: {Radius}";

Here, we’re simply returning a string that describes the circle in terms of its radius using string interpolation. String.Format is conspicuously missing and rather than a numeric placeholder we directly reference the Radius property within the string literal. Just as with String.Format, we can also include format and alignment specifiers within the holes. Here’s the ToString method showing the radius to two decimal places:

public override string ToString() => $"Radius: {Radius:0.00}";

One of the things that makes string interpolation so exciting is that we’re not limited to simple identifiers; we can also use expressions. For instance, if our ToString method was supposed to show the circle’s area instead, we could include the expression directly as follows or even invoke a method:

public override string ToString() => $"Area: {PI * Pow(Radius, 2)}";

The ability to include expressions within interpolated strings is really powerful but, as Bill Wagner recently pointed out, the compiler can get tripped up on some things. Bill notes the conditional operator as one such scenario. When the conditional operator is included in a hole the colon character confuses the compiler because the colon is used to signify both the else part of the conditional operator and to delimit the format specifier in the hole. If this is something you run into, simply wrap the conditional in parenthesis to inform the compiler that everything within the parens is the expression.

Null-Conditional Operators

Finally we come to the fifth and final new feature in this list; a feature I consider to be a necessary evil: the null-conditional operators. The null conditional operators are a convenient way to reduce the number of null checks we have to perform when drilling down into an object’s properties or elements by short-circuiting when a null value is encountered. To see why this is useful consider the following scenario.

Imagine you have an array of objects that represent some type of batch job. These objects each have nullable DateTime properties representing when the job started and completed. If we wanted to determine when a particular job completed we’d not only need to make sure that the item at the selected index isn’t null but also that the completed property isn’t null, either. Such code might look like this:

DateTime? completed = null;

if(jobs[0] != null)
{
    if(jobs[0].Completed != null)
    {
        completed = jobs[0].Completed;
    }
}

WriteLine($"Completed: {completed ?? DateTime.MaxValue}");

That’s quite a bit of code for something rather trivial and it distracts from the task of getting the completed time for a job. That’s where the null-conditional operators come in. By using the null-conditional operators, we can reduce the above code to a single line:

WriteLine($"Completed: {jobs?[0]?.Completed ?? DateTime.MaxValue}");

This snippet demonstrates both of the null-conditional operators. First is the ? ahead of the indexer. This returns if the element at that index is null. Next is the ?. operator which returns if the member on the right is null. Finally, we see how the null-conditional operators can be used in conjunction with the null-coalescing operator to combine the giant if block into a single expression.

So why do I consider this feature a necessary evil? The reason is that I consider null to be evil, null references have been called The Billion Dollar Mistake, and Bob Martin discussed the evils of null in Clean Code. In general, nulls should be avoided and dealing with them is a costly nuisance. I think that these null-conditional operators, which are also sometimes collectively referred to as the null-propagation operators, will do just what that name implies – rather than promoting good coding practices where null is avoided, including the null-conditional operators will encourage developers to sloppily pass or return null rather than considering whether null is actually a legitimate value with the context (hint: it’s not). Unfortunately, null is an ingrained part of C# so we have to deal with it. As such, the null-conditional operators seem like a fairly elegant way to reduce null’s impact while still allowing it exist.

Wrap-up

There you have it, my five favorite C# 6 language features: auto-property initialization enhancements, using static, expression-bodied members, string interpolation, and the null-conditional operators. I recognize that some popular features such as the nameof operator and exception filters didn’t make the cut. While I definitely see their appeal I think they’re limited to a few isolated use cases rather than serving as more general purpose features and as such I don’t anticipate using them all that often. Did I miss anything? Let me know in the comments.

Functional C#: Fluent Interfaces and Functional Method Chaining

This is adapted from a talk I’ve been refining a bit. I’m pretty happy with it overall but please let me know what you think in the comments.

Update: I went to correct a minor issue in a code sample and WordPress messed up the code formatting. Even after reverting to the previous version I still found issues with escaped quotes and casing changes on some generic type definitions. I’ve tried to fix the problems but I may have missed a few spots. I apologize for any odd formatting issues.

I’ve been developing software professionally for 15 years or so. Like many of today’s enterprise developers much of my career has been spent with object-oriented languages but when I discovered functional programming a few years ago it changed the way I think about code at the most fundamental levels. As such I no longer think about problems in terms of object hierarchies, encapsulation, or and associated behavior. Instead I think in terms of independent functions and the data upon which they operate in order to produce the desired result. (more…)

Busy Week Ahead

[12/15/2014 Update] Due to time concerns FunScript has been dropped from the Indy F# meeting. If you were really looking forward an introduction to FunScript stay tuned – we’ll be coming back to it in a few months.

This is a busy week for me on the community front with talks at multiple Indianapolis user groups. If either of these topics interest you I hope you’ll register and join us.

Indy F#

Double Feature: Type Providers and FunScript
Type Providers

Tuesday, December 16, 7:00 PM
Launch Fishers (info and registration)

On Tuesday I’ll be kicking off an Indy F# double feature by talking about Type Providers. We’ll begin with a short tour of several existing type providers and seeing how they make accessing data virtually effortless. With a good taste of what type providers can do we’ll then look behind the curtain to see how they work by walking through creating a custom type provider that reads ID3 tags from MP3 files.

Brad Pillow will follow with an introduction to building single-page applications with FunScript.

Indy Software Artisans

TypeScript: Bringing Sanity to JavaScript
Thursday, December 18, 5:30 PM
SEP (info and registration)

On Thursday I’ll change gears from F# to TypeScript. If writing JavaScript frustrates you or you just want to be more productive when developing browser-based applications you’ll definitely want to check out TypeScript. This session is not only a tour of TypeScript’s language features but also highlights the resulting JavaScript code. To help showcase how TypeScript can fit into your new or existing projects, the demo application is an AngularJS and Bootstrap application driven entirely by TypeScript.

Fun with Code Diagnostic Analyzers

A few days ago I posted an article detailing how to construct a code diagnostic analyzer and code fix provider to detect if..else statements that simply assign a variable or return a value and replace the statements with a conditional operator. You know, the kind of things that code diagnostic analyzers and code fix providers are intended for. As I was developing those components I got to thinking about what kind of fun I could have while abusing the feature. More specifically, I wondered whether could I construct a code diagnostic analyzer such that it would highlight every line of C# code as a warning and recommend using F# instead.

It turns out, it’s actually really easy. The trick is to register a syntax tree action rather than a syntax node action and always report the diagnostic rule at the tree’s root location. For an extra bit of fun, I also set the diagnostic rule’s help link to fsharp.org so that clicking the link in the error list directs the user to that site.

Here’s the analyzer’s code listing in its entirety:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

namespace UseFSharpAnalyzer
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class UseFSharpAnalyzerAnalyzer : DiagnosticAnalyzer
    {
        internal static DiagnosticDescriptor Rule =
            new DiagnosticDescriptor(
                "UseFSharpAnalyzer",
                "Use F#",
                "You're using C#; Try F# instead!",
                "Language Choice",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                helpLink: "http://fsharp.org");

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

        public override void Initialize(AnalysisContext context)
        {
            context.RegisterSyntaxTreeAction(AnalyzeTree);
        }

        private static void AnalyzeTree(SyntaxTreeAnalysisContext context)
        {
            var rootLocation = context.Tree.GetRoot().GetLocation();
            var diag = Diagnostic.Create(Rule, rootLocation);

            context.ReportDiagnostic(diag);
        }
    }
}

When applied to a C# file, the result is as follows:

Use F# Analyzer

This is clearly an example of what not to do with code analyzers but it was fun to put together and see the result nonetheless. If you’ve thought of any other entertaining uses for code analyzers, I’d love to hear about them!

I Can Analyze Code, And So Can You

[12 December 2014 – Update 1] Upon setting up a new VM I realized that I missed a prerequisite when writing this post. The Visual Studio 2015 Preview SDK is also required. This extension includes the VSIX project subtype required by the Diagnostic and Code Fix template used for the example. I’ve included a note about installing the SDK in the prerequisites section below.

[12 December 2014 – Update 2] The github project has moved under the .NET Analyzers organization. This organization is collecting diagnostics, code fixes, and refactorings like to showcase the capabilities of this technology. The project link has been updated accordingly.

Over the past several years, Microsoft has been hard at work on the .NET Compiler Platform (formerly Roslyn). Shipping with Visual Studio 2015 the .NET Compiler Platform includes a complete rewrite of the C# and Visual Basic compilers intended to bring features that developers have come to expect from modern compilers. In addition to the shiny new compilers the .NET Compiler Platform introduces a rich set of APIs that we can harness to build custom code diagnostic analyzers and code fix providers thus allowing us to detect and correct issues in our code.

When trying to decide on a useful demonstration for these features I thought of one of my coding pet peeves: using an if..else statement to conditionally set a variable or return a value. I prefer treating these scenarios as an expression via the conditional (ternary) operator and I often find myself refactoring these patterns in legacy code. It certainly would be nice to automate that process. It turns out that this is exactly the type of task at which diagnostic analyzers and code fix providers excel and we’ll walk through the process of creating such components in this post. (more…)

Musings on C#’s Evolution

Since completing my series on likely C# 6.0 features and reviewing the draft spec for record classes and pattern matching in C#, I’ve had some time to reflect on how C# has evolved and think about where it’s going from a more holistic perspective.

I’ve been working with C# for approximately 12 years. It was the language of choice at the beginning of my career so, in a sense, C# and I have grown up together. During that time I’ve watched what was essentially a Java clone grow into the powerhouse it is today. It’s a bit cliché, but when I started working with C# it didn’t have many of the features I now take for granted. Things like generics, the null coalescing operator, lambda expressions, extension methods, anonymous types, dynamics, and async/await were in their infancy with some as much as a decade away. It seems that every major release has brought a slew of compelling new features that have dramatically improved the language.

As I look at the code I write today I often wonder how C# developers managed without generics. I remember the headaches of dealing with ArrayList and its early kin and having to trust that the objects in the collections were actually the types we thought they were. Today I often look at blocks of imperative code (typically loops) that see that they’re doing nothing more than explicitly filtering, mapping, and reducing sequences. I immediately think how much cleaner the code would be with LINQ. And in today’s world of connected mobile devices where application responsiveness is of primary importance, async/await make asynchronous development accessible to the masses. These are all incredible tools we have at our disposal and are all among the reasons I’ve stuck with .NET development for so long.

C# 6 is different. With C# 6, the language enhancement is the Roslyn compiler. Roslyn promises to bring modern compilation strategies to C#. This is a huge undertaking and heavily impacts how we’ll interact with code through Visual Studio and other tools. I haven’t looked at Roslyn nearly as much as I’d like but I do believe the new compiler is long overdue and will pay dividends in the long run for developers and Microsoft alike. That said, the actual changes to the C# language itself seem to range from lackluster to pointless.

I’m not saying that the language features are all bad; several of them will likely be welcome additions to the language. Enhancements such as primary constructors, auto-implemented property initializers, and using static are each things that can have an immediate impact on developer productivity and are by far my favorites of the lot. Other features, such as index initializers, params IEnumerable<T>, and expression-bodied members don’t really seem to add much to the language due to either existing syntactic constructs or other limitations of the language.

Is initializing dictionary elements with [7] = "seven" really any better than with { 7, "seven" }? All the index initializer achieves is trading a pair of curly braces and a comma for a pair of square brackets and an assignment operator, respectively. How is params IEnumerable<int> better than params int[] if the argument list is still converted to an array at the call site and no other usage requires defining the parameter with the params modifier? Finally, expression-bodied members could be a great feature if C# was an expression-based language but it’s not – it’s statement-based. The proposed semicolon operator could greatly increase the usefulness of expression-bodied members but at the time of this writing, it’s still listed as “Maybe” on the Language Feature Implementation Status page. Even then, the semicolon operator feels like an attempt to coerce C# into being expression-based when it was never intended to be treated as such. In the meantime, there’s already a perfectly viable alternative – write a function!

Looking further into the future brings us to the draft spec for record classes and pattern matching. (Please note that since this spec is a draft, everything here is subject to change; whatever does get implemented, if anything, may or may not look like this proposal.) If you haven’t read the draft (and I highly recommend that you do), it proposes a new record modifier for class definitions. This modifier would instruct the compiler to generate an immutable class with built-in structural equality and an is operator (if not provided). The is operator can then be used in if and switch statements for type checking and value extractions.

For example, we could define a class like this (example taken from the proposal):

public record class Cartesian(double x: X, double y: Y);

…then use pattern matching constructs like this (adapted from the proposal):

if (expr is Cartesian c)
{
  // code using c
}

My initial reaction when I heard about these features was excitement but the more I read and the more I think about it, the less I like them, pattern matching in particular. I’ll be the last person to argue against immutability and pattern matching, especially when looking at them from a functional programming mindset. I do like the simplicity of the immutable record classes and I don’t mind that pattern matching is essentially an extension of the is operator.

The reason I don’t like these features as proposed is that they don’t feel like they belong in C#. I feel like this for a few reasons. First, pattern matching can improve code’s expressiveness but merely adding it to a language that wasn’t constructed with pattern matching in mind severely limits its usefulness. Second, the overall expressiveness is again limited by the fact that C# isn’t an expression-based language; pattern matching might make if statements and switch statements more concise, it doesn’t change the fact that they’re still statements!

Let’s contrast the proposal with an expression-based language where pattern matching is already a central concept: F#. As an expression-based language, virtually everything in F# is an expression. This includes familiar constructs like ifs and matches. By definition, as expressions these constructs return values – there’s no need to rely on mutability or wrap the behavior within a separate function, returning from each branch as we must in a statement-based language. For example, this is valid F#:

let x = if System.Random().Next(10) % 2 = 0 then "even" else "odd"

You could correctly argue that C# provides the conditional operator for this scenario but that doesn’t change the fact that in C#, if is a statement whereas in F# it’s an expression. Furthermore, what’s probably not apparent here if you’re not familiar with F# is that binding x is a pattern match. You can see this in action by replacing x with an underscore (F#’s wildcard pattern matches everything and tosses out the result) as follows:

let _ = if System.Random().Next(10) % 2 = 0 then "even" else "odd"

If you evaluate the expression in F# Interactive (FSI) you’ll see that it executes successfully but no value is bound as we’d expect due to the wildcard. For further proof, this is also how tuple binding works as evidenced here:

let value, category =
  let r = System.Random().Next(10)
  r, if r % 2 = 0 then "even" else "odd"

The expression following the assignment in the above snippet returns a tuple containing a random value and whether that value is even or odd. The tupled items are then bound to value and category respectively by using pattern matching.

Pattern matching completely permeates F#. It’s not restricted to match expressions or inline bindings; it even works in function signatures and as a filter in looping constructs! The C# proposal doesn’t talk about pattern matching outside the context of if statements and switches so discussing whether C# will embrace pattern matching as fully as F# is pure speculation but it certainly doesn’t sound particularly promising at this point. Even if pattern matching is supported outside of if and switch statements, it’s still the same underlying statement-based language.

My point in writing all of this is that for years C# has been becoming increasingly functional, with the strongest push coming in version 3 and subsequent releases building upon that foundation. Many of the features in C# 6.0 continue even further down that path by elevating expressions an even more important concept within the language. Finally, a future incarnation of the language will likely include some form of immutable class syntax and pattern matching. If this is the direction that C# is going, my question is this: Why wait for it? Why not learn a functional language to at least supplement the object-oriented language you already know?

The C# of the future is already here and it’s called F#. F# already has a modern compiler; it already supports many of the things slowly making their way into C# and much, much more. In other words, there’s no reason to wait for these things to make it into C# because F# already does them! Incorporating F# into your existing solutions isn’t a mutually exclusive proposition. As a CLR language, F# compiles to the same IL, targets the same runtimes (with few exceptions), and uses the same libraries with which you’re already familiar. In many cases it’s a perfect complement to or replacement for existing C# code.

I challenge you to try F#. Experiment with the features; see how many things you can spot that are “recent” additions to C#, making their way to C#, or not possible at all. I think you’ll be pleasantly surprised at how adopting an expression-based, functional-first language can change the way you think, improve the quality of your code, and make you more productive. If you accept this challenge, I recommend checking out my book or any of the great resources listed on my Learning F# page to get you started.

My Next Language – Results

Last week I asked my social media network to help choose my destiny by suggesting which language I should study next. In all, I received 15 responses. Thanks to everyone that contributed to this.

When I put the survey together I hadn’t completely decided how I’d select a winner. Would I select based on the number of votes or would there be a really compelling reason to select something with only a single vote? After inspecting the responses, it looks like Haskell is the clear winner. To be honest, I was really hoping to get more votes and reasons for Erlang but it’s really hard to ignore the fact that Haskell received a third of the votes. What really surprised me was the number of “Other” votes and the languages that were suggested.

For those interested, I’ve listed the results along with comments below. Now to find some time to start studying Haskell!

Results

Language Survey Results

Haskell

  • Pure functional is a natural next step after mostly functional F#
  • Going from Haskell to F# is frustrating. But the other way around is actually compelling
  • Typeclasses/-kinds, purity, better type inference and pattern matching, higher-kinded/ranked polymorphism, lean syntax.

Other

  • Rust – Speed of C, but more safe. Language is still under development, so you could go 2/2 on being a hipster.
  • Idris/Coq/Agda – Dependent types
  • Elixir – Erlang on steroids/for the masses.
  • Rebol – Rich built-in types, homoiconicity, consistency, cross-platform, small, zero-install just download and run, super easy GUI development built-in (at least Rebol 2.7..) and then you can write a book on it too!

Python

  • Market demand
  • Popular choice among UNIX crowd, has a .NET implementation, can show how people unfamiliar with .net interact with windows with it.

Erlang

  • Immutable by default
  • Let it fail thinking vs catch-all errors
  • Functional

Ruby

  • Ignore the rails stuff, ruby is a wonderful language with a lot of interesting features (modules, execution model, monkey patching aka nothing is closed, blocks).

R

  • No comments