Lesson 5. Trusting the compiler

 

The compiler is one of the most important features in any language. In a language such as F#, where the compiler does a lot of heavy lifting for you, it’s particularly important that you understand the role it plays in your day-to-day development cycle. In this lesson

  • You’ll look at the F# compiler from a developer’s point of view (don’t get scared!).
  • You’ll focus specifically on one area of it: type inference.
  • You’ll recap what type inference is from a C# / VB .NET perspective.
  • You’ll look at how F# takes type inference to the next level.

5.1. Type inference as we know it

Unless you’ve used only earlier versions of C#, you’ll almost certainly be familiar with the var keyword. Let’s refamiliarize ourselves with the var keyword based on the official MSDN documentation:

Variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

5.1.1. Type inference in C# in detail

Here’s a simple example of that description in action.

Listing 5.1. Using var in C#
var i = 10;          #1
int i = 10;          #2

The right-hand side of the = can be just about any expression, so you can write more-complicated code that may defer to another method, perhaps in another class. Naturally, you need to give a little bit of thought regarding the naming of variables when using var!

5.2. F# type-inference basics

5.3. Following the breadcrumbs

Summary