United Kingdom: +44 (0)208 088 8978

Support for nameof in F# 5

One of the new features in the F# 5 release is the addition of the nameof function. Let's see what it does!

F# 5 was released alongside .NET 5 a couple of weeks ago. It has many new and exciting features to talk about, and in this post we will be taking a look at one of them - the nameof function. The nameof function produces the name of an identifier, type, or member as a string constant.

A Simple Example

Let's say that we have the following binding:

let me = "Alican Demirtas"

If we go ahead and use the nameof function on the me keyword, like so:

nameof me

This will produce the following result:


Use Cases

Seemingly a small addition, nameof is useful when throwing exceptions:

failwith $"The parameter '{nameof me}' is is invalid."

... or when logging information:

log $"The function {nameof myFunc} was called."

More Examples

Considering we have the following DU, modules and the type alias...

type Department =
    | Development
    | Operations

module Mathematics =
    let addition a b = a + b

    module Advanced =
        let squared a = a * a

type Number = int

...below is a block of code going through the return value of the nameof function being applied to each of these.

nameof Department // result: Department
nameof Department.Development // result: Development
nameof Mathematics.addition // result: addition
nameof Mathematics.Advanced.squared // result: squared
nameof Number // result: Number

As you can see, the nameof function will always return the name of the identifier passed to it. Meaning that when we use a fully qualified name of a function located in a module such as Mathematics.addition, it will only return "addition". Also, when we use it on a type alias such as Number above, it will return the alias rather than the actual type.

Closing Thoughts

The nameof function will surely come in handy for exceptions and logging, but what do you think about it? Will you start using it, or keep on logging things the old way?