Environment Variables in F#

Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in F#.

open System
open System.Collections

// To set a key/value pair, use Environment.SetEnvironmentVariable.
// To get a value for a key, use Environment.GetEnvironmentVariable.
// This will return null if the key isn't present in the environment.

Environment.SetEnvironmentVariable("FOO", "1")
printfn "FOO: %s" (Environment.GetEnvironmentVariable("FOO"))
printfn "BAR: %s" (Environment.GetEnvironmentVariable("BAR"))

// Use Environment.GetEnvironmentVariables to list all key/value pairs in the
// environment. This returns an IDictionary. Here we print all the keys.

printfn ""
for entry in Environment.GetEnvironmentVariables() do
    let de = entry :?> DictionaryEntry
    printfn "%O" de.Key

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is null (or an empty string when printed).

FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

The list of keys in the environment will depend on your particular machine.

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 dotnet run
FOO: 1
BAR: 2
...

In F#, we use the System.Environment class to work with environment variables. The SetEnvironmentVariable and GetEnvironmentVariable methods are used to set and get environment variables respectively. The GetEnvironmentVariables method returns all environment variables as an IDictionary.

Note that in F#, we use printfn for formatted printing, which is similar to printf in other languages but adds a newline at the end.

The open statements at the beginning are similar to import statements in other languages, allowing us to use types from the specified namespaces without fully qualifying them.